Stuck in loop while trying to get input from cin

只愿长相守 提交于 2019-12-11 23:42:10

问题


Okay I'm very new to C++, I'm experianced with C# and I don't really know what is wrong in my code. I'm just trying to figure out how to check whether the user's input is a integer or string.

But when I type 'a' or some other string, the while loop never ends.

    #include <iostream>

using namespace std;

int main ()
{
    int number;
    goto skip;
    do
    {
        cout << "Wrong input. Try again.";
skip:
        cout << "Number: ";
        cin >> number;
    }
    while (!cin);
    cout << "Correct input.";
    system("PAUSE");
}

回答1:


Once your stream has gone into failure mode it will stay in failure mode until you clear() its state bits. However, merely clearing the bits won't help because the offending character will stay in the stream. Most likely you want to ignore the entire line before retrying:

while (!(std::cout << "Number: " && std::cin >> number)) {
    std::cout << "Wrong input. Try again.\n";
    std::cin.clear();
    std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
}
std::cout << "Correct input.\n";
std::cin.ignore();


来源:https://stackoverflow.com/questions/19128005/stuck-in-loop-while-trying-to-get-input-from-cin

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!