c++ if(!cin)导致循环

C++ if(!cin) causes loop

本文关键字:循环 cin if c++      更新时间:2023-10-16

我尝试使用if(!cin)来验证用户输入是否真的是整数。然后我的程序就进入了一个无限循环从来没有要求新的输入

do{
    cin >> temp->data;
    if(!cin){
        cout << "Please enter a Number!" << 'n';
        correct=false;
        }
   }while(correct==false);

如果有人能帮我就太好了:)

当std::cin读取输入失败时,将设置相应的错误标志。因此,您需要使用std::cin.clear()重置标志,以便下一个输入操作能够正常工作,然后使用std::cin.ignore(.)跳过所有内容,直到新行,以避免类似的格式化输入。

while (!(std::cin >> temp->data))
{
        std::cin.clear();
        std::cin.ignore(std::numeric_limits<std::streamsize>::max(), 'n');
        std::cout << "nPlease enter a number!" << std::endl;
}

std::numeric_limits<std::streamsize>::max()返回一个流可以容纳的最大字符数,从而保证忽略整行。

如果您想做这种检查,请将数据从cin读取到string并将string转换为数字:

string str;
do{
    cin >> str;
    if(!cin){
        cout << "Please enter a Number!" << 'n';
        correct=false;
        }
    else{
        istringstream stream(str);
        stream >> temp->data;
        if(!stream){
            cout << "Please enter a Number!" << 'n';
            correct=false;
        }
     }
   }while(correct==false);

使用cin.fail()检查用户输入是否正确。如果最后一个cin命令失败,cin.fail()返回true,否则返回false。此外,您的循环可能是无限的,因此您还必须声明一个else,将检查标志correct设置为true。因此,要使循环的条件无效并在用户输入正确输入的情况下退出循环(参见下面的代码):

do{
    cin >> temp->data;
    if(cin.fail()){
        cin.clear();
        cin.ignore(10000, 'n');
        cout << "Please enter a Number!" << 'n';
        correct=false;
     } else {
        correct=true;
     }
}while(correct==false);

你的'正确'变量实际上不做任何你正在使用它的方式。如果correct不为真,则不可能退出循环;所以你可以去掉它,当你读到数字时,只使用一个循环退出命令。

而且,到目前为止发布的答案都没有处理正在关闭的输入。在这种情况下,它们会进入一个无限循环。

// A loop; we will break out when we successfully read a number.
while ( 1 )
{
// Prompt for a number and read it
    cout << "Please enter a Number!" << endl;
    cin >> temp->data;
// Exit loop if we successfully read
    if ( cin )
         break;
// Check to see if we failed due to the input being closed
    if ( cin.eof() )
    {
        cerr << "End of input reached.n";
        return 0;   // depends what your function returns of course
    }
// reset the error condition that was caused by trying to read an integer and failing
    cin.clear();
// discard anything they previously typed
    cin.ignore(numeric_limits<streamsize>::max(), 'n');
}

从这里开始,一个好的设计应该是让这个代码本身成为一个完整的函数。然后,您可以在需要安全地获取数字时调用该函数,而无需重复代码。函数声明可以是:

void input_number(int &the_number, std::istream &in, std::string prompt);

将输出the_number,并且它将通过抛出异常或依靠调用者检查!cin甚至返回bool来处理文件结束;

例如,如果在if语句的条件前放置" ! "。这应该是一个非操作符