Module 00 - Marymota/CPP_Modules GitHub Wiki

Ex01

While loop in a C++ manner

A while loop using std::cin can be implemented like this: while(std::cin)

Resource:
Character Input in While Loop Using C++


Reading input | cin.clear | cin.ignore

While reading input with cin errors may occur (i.e. passing a string value to an integer variable cin >> i).
To protect from undefined behavior we can add the input request inside a if statement (i.e. if(!(cin >> i))).
If an error occurs then an error flag is set and future attempts to get input will fail.
Then using cin.clear() we clear the error flag on cin (so that future I/O operations will work correctly), and then cin.ignore(10000, '\n') skips to the next newline (to ignore anything else on the same line as the non-number so that it does not cause another parse failure).
10000 is a random number that assumes that the user will not insert a long invalid value.

Resource:
Why would we call cin.clear() and cin.ignore() after reading input?


Couldn't solve the problem with input of special characters (i.e. ç)