while循环中的C ++ cin输入验证

问题描述 投票:1回答:2

除了一个小问题,我的代码大多数都能正常工作。虽然它只应接受整数,但它也接受以整数开头的用户输入,例如6abc。我看到了针对此here的修复程序,但它将输入类型更改为字符串,并增加了很多代码行。我想知道是否有更简单的方法来解决此问题:

int ID;
cout << "Student ID: ";
// error check for integer IDs
while( !( cin >> ID )) {
    cout << "Must input an integer ID." << endl ;
    cin.clear() ; 
    cin.ignore( 123, '\n' ) ; 
}
c++ validation cin
2个回答
0
投票

总而言之-号

但是您可以做的是先将整个单词读入string,然后将整个单词转换为int,检查该转换是否有错误,例如:

int ID;
string input;

do
{
    cout << "Student ID: ";
    if (!(cin >> input))
    {
        cin.clear();
        cin.ignore(numerric_limits<streamsize>::max(), '\n');
    }
    else
    {
        size_t pos = 0;
        try
        {
            ID = stoi(input, &pos);
            if (pos == input.size())
                break;
        }
        catch (const std:exception &) {}
    }
    cout << "Must input an integer ID." << endl;
}
while (true);

-1
投票

最好的方法是使用字符串,就像您在问题中已经提到的那样。但是,如果您不想使用字符串,则可以使用getch()函数。

使用getch,您可以逐位获取输入数字。检查每个数字ASCII代码是否在'0'和'9'之间(或者您可以通过使用isdigit函数来完成此操作)。如果用户输入了无效数字,您可以要求他们再次输入。

您可以通过执行以下操作来建立您的号码:

int number = 0;
while(c = getch())
{
    if(c >= '0' && c <='9')
    {
       number *= 10;
       number += (c-'0')
    }
}
© www.soinside.com 2019 - 2024. All rights reserved.