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
c开发者_运维问答out << "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 :/
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
}
精彩评论