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 is caused by invalid input to cin
.
You can add error handling to avoid such issue by following:
change
cin >> first_name >> age;
cout << "Hello, " << first_name << " (age " << age << ")\n";
to
cin >> first_name;
while (!(cin >> age)) {
cout << "Invalid age, please re-enter.\n";
cin.clear();
cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
}
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.