If cin >> num fails, the invalid input must be removed from the stream. I suggest using ignore instead of sync to accomplish this. The reason in sync not guaranteed to remove the remaining input in all implementations of the standard library.
#include <iostream>
The above example uses std::numeric_limits<std::streamsize>::max() used to extract the maximum number of characters that the input buffer can hold. This allows ignore() remove as many characters as possible before a new line. This is idiomatic C ++ and it is preferable to use magic numbers , which are likely to hide the problem that you currently have.
This works well, but does not handle situations where the input contains extra characters after the number. To deal with these situations, the cycle needs to be slightly modified to handle additional validation. One option is to read the whole line from cin , put it in std::stringstream , read the number from it, and then do an additional check. There is one special case that may need to be taken into account, although this is a line where the only characters after the number are spaces. Fortunately, the standard library provides a stream modifier std::skipws , which makes it easy to handle the situation. The example below shows how to do this without much effect.
#include <iostream> #include <sstream> int main() { int num; for(;;) { std::cout << "Enter a number: " << std::flush; std::string line; std::getline(std::cin, line); // Read a line from console std::stringstream text(line); // store in a string stream char ch = 0; if(!(text >> num).fail() && (text >> std::skipws >> ch).fail()) { break; } std::cout << "Invalid input; please re-enter.\n"; } return 0; }
The expression (text >> std::skipws >> ch).fail() skip all spaces that appear after the number, and then try to read one character. If the character is not available, reading will not be issued if the user enters only the number and nothing more. If we try to do this with cin , it will wait for the user to enter more text, even if the input is valid.
source share