开发者

Why does this cin loop never end?

开发者 https://www.devze.com 2023-02-08 09:45 出处:网络
In the following code, if the user inputs something that is not an int, the program goes into an infinite loop.Why does this happen, and what should I do to fix it?

In the following code, if the user inputs something that is not an int, the program goes into an infinite loop. Why does this happen, and what should I do to fix it?

开发者_如何学Python
#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. 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. Using an if statement tries to read a value and then let's you know whether or not it succeeded.

Additionally, this really isn't a good way to read from cin. It's brittle and any invalid input can totally take down your program, since gets is inherently unsafe. 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

0

精彩评论

暂无评论...
验证码 换一张
取 消