【问题标题】:stuck on with input validation in c++ either string or integer坚持使用 C++ 中的输入验证,无论是字符串还是整数
【发布时间】:2023-03-04 07:55:09
【问题描述】:

我正在尝试在 C++ 中练习我的输入验证。当要求用户输入数字或字符串时,如何让程序验证用户输入? 这是我的代码示例。

public:
void CreateProduct() {
inputProduct:
    system("cls");
    cout << "\n\n\n\n\n\n\n\t\t\t\tPLEASE PROVIDE ACCURATE INFORMATION";
    cout << "\n\n\t\tPRODUCT NUMBER: ";
    cin >> ProductNumber;
    if (!cin) {
        cout << "\nPlease provide an integer";
        cin.clear();
        cin.end;
        goto inputProduct;
       //when enter a string i should enter this if statement and exit
       // to be asked for another entry but am getting stuck in a loop.
    }
    system("cls");
    cout << "\n\n\n\n\n\n\n\t\t\t\tPRODUCT NAME: ";
    cin >> ProductName;
    system("cls");
    cout << "\n\n\n\n\n\n\n\t\t\t\tPRICE: ";
    cin >> Price;
    system("cls");

}

请帮助我理解这个输入验证。

【问题讨论】:

  • 有什么特别不明白的地方?
  • 如果它是一个整数条目,它不应该接受文本或字符串。
  • 你的意思是如果你输入一个整数,它不会跳过if (!cin) { ...
  • 它会跳过,但如果它不是整数,它就会陷入循环。
  • @WillieMwewa 摆脱 goto 并使用 do - while 循环。

标签: c++ validation input console


【解决方案1】:

您可以通过检查输入中每个字符的ascii值来检查输入是否为数字。

 #include <iostream>
#include <cstring>
#include <string>

int main(void)
{
    std::string str;

    std::cin>>str;

    bool isNumeric = true;
    for(size_t i=0;i<str.length();++i)
    {
        if(str[i]< '0' || str[i] > '9')
        {
           isNumeric = false;
          break;
        }
    }

    if(!isNumeric)
    {
        std::cout<<"Input is not an integer";
        exit(1);
    }
    return 0;
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-04-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-12-14
    相关资源
    最近更新 更多