Aren't you allowed to study ahead in the university?
Ok. This part is all that you need right now. The other half is usefull in more complex situations where escape sequences are used to terminate input with CTRL+Z/X.
Code:
cin.clear();
cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
cin.clear();
First we clear the stream in case some error occured. Let's start with a blank sheet.
cin.ignore(...
We are going to ignore a certain amount of stuff left in the stream.
std::numeric_limits<std::streamsize>::max()
How much are we going to ignore? Well, let's ignore the maximum number of items a stream can have...
'\n'
...until we find a newline.
#include <climits>
But to use the nice feature of
numeric_limits<>max(), we need to include this header.
std::
Let's use definitions only defined by the ISO C++ standard.
using std::endl;
using std::cout;
using std::cin;
It is handy if these often used functions (endl, cout, and cin), can be typed without typing "std::" in front of it all the time. So let's predefine that we want to use the ISO C++ versions only.
Next time when we type "cout<<", the compiler knows we mean the ISO version "std::cout<<".
Another way
Code:
void reset_istream(std::istream & is)
{
char ch;
// Reset the state.
is.clear();
// Remove all characters until we find a newline or EOF.
ch = is.get();
while ((ch != '\n')&&(ch != EOF))
ch = is.get();
is.clear();
}
Use it like this:
Code:
reset_istream(std::cin);