user1046403
user1046403

Reputation: 555

Stuck in loop while trying to get input from cin

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");
}

Upvotes: 0

Views: 1109

Answers (1)

Dietmar K&#252;hl
Dietmar K&#252;hl

Reputation: 153840

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();

Upvotes: 4

Related Questions