坚持用c ++中的输入验证字符串或整数

时间:2015-05-14 11:57:36

标签: c++ validation input console

我正在尝试用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");

}

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

1 个答案:

答案 0 :(得分:-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;
}