I ran the following code twice.
Once when I input Carlos 22
, the program ran correctly and keep_window_open()
apparently worked as the console
This happens because the implementation of keep_window_open()
doesn't ignore any characters already in the buffer.
from Stroustrup's site:
inline void keep_window_open()
{
cin.clear();
cout << "Please enter a character to exit\n";
char ch;
cin >> ch;
return;
}
Here, cin.clear()
will clear the error flag so that future IO operations will work as expected. However, the failure you have (trying to input Carlos
into an int
) leaves the string Carlos
in the buffer. The read into ch
then gets the C
and the program exits.
You can use cin.ignore()
to ignore characters in the buffer after this type of error. You can see that void keep_window_open(string s)
in the same file immediately below void keep_window_open()
does exactly this.