Will03uk
Will03uk

Reputation: 3444

How do I use iostream cin properly?

This may at first seem like an odd question, but when a cin request is made, if it receives the wrong type it still continues but the status of cin changes.

How do I loop until cin is OK, e.g. when I ask for a number it "accepts" a string if no extra code is given e.g. a loop?

Finally when I use cin multiple times in a row it does the first cin as expected but then skips the rest; how do I fix this? If you need more information just ask in a comment.

// Example
cout << "Enter a number: ";
cin >> num; // A string is given

cout << "Enter another number: ";
cin >> num2;

In the example above the string would be kinda accepted and the second cin would most likely skip for some reason. I had a while ago find the answer to this question but I lost the snippet of the loop I used so :/

Upvotes: 1

Views: 3793

Answers (1)

Benjamin Lindley
Benjamin Lindley

Reputation: 103751

example:

int value;
while(!(cin >> value))
{
    cin.clear();
    cin.ignore();  // eat one character
}

while(!(cin >> value))
{
    cin.clear();
    cin.ignore(10000,'\n');  // eat the rest of the line
}

Upvotes: 2

Related Questions