简体   繁体   English

为什么这个 cin 循环永远不会结束?

[英]Why does this cin loop never end?

In the following code, if the user inputs something that is not an int , the program goes into an infinite loop.在下面的代码中,如果用户输入的内容不是int ,程序将进入无限循环。 Why does this happen, and what should I do to fix it?为什么会发生这种情况,我应该如何解决?

#include <iostream>
#include <string>
using namespace std;


int main()
{
    int i;
    char str[100];
    while (!(cin >> i))
    {
        gets(str);
        cout << "failure read!" << endl;
    }

    cout << "successful read!" << endl;
    return 0;
}

Clear the error state:清除错误状态:

int main()
{
    int i;
    char str[100];
    while (!(cin >> i))
    {
        cin.clear();
        cin.getline(str,100);
        cout << "failure read!" << endl;
    }

    cout << "successful read!" << endl;
    return 0;
}

I think that you want to replace the while loop with an if statement, with this loop, you'll continuously read from cin while an error occurs.我认为您想用 if 语句替换 while 循环,使用这个循环,您将在发生错误时不断地从 cin 中读取。 However, cin is structured so that after an error occurs, you must manually clear the error state, and since you're not doing that here this will go into an infinite loop.然而,cin 的结构使得在发生错误后,您必须手动清除错误状态,并且由于您在这里没有这样做,这将进入无限循环。 Using an if statement tries to read a value and then let's you know whether or not it succeeded.使用 if 语句尝试读取一个值,然后让您知道它是否成功。

Additionally, this really isn't a good way to read from cin.此外,这确实不是从 cin 读取的好方法。 It's brittle and any invalid input can totally take down your program, since gets is inherently unsafe.它很脆弱,任何无效输入都可能完全破坏您的程序,因为 gets 本质上是不安全的。 For a discussion of a safer and more robust way to get input in C++, check out http://www.stanford.edu/class/cs106l/course-reader/Ch3_Streams.pdf有关在 C++ 中获取输入的更安全、更可靠的方法的讨论,请查看http://www.stanford.edu/class/cs106l/course-reader/Ch3_Streams.pdf

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM