0

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 window stayed open, and displayed the "Please enter a character to exit" message.

But when I input 22 Carlos the program works as expected but the keep_window_open()does not work - it simply closes as if I did not have that line in there at all.

What is the reason for this behavior? And what is the best way I can keep the window open in all circumstances?

My code:

#include "std_lib_facilities.h"

// read name and age
int main()
{
    cout << "please enter your name and your age\n";
    string first_name =  "???";
    int age = -1;
    cin >> first_name >> age;
    cout << "Hello, " << first_name << " (age " << age << ")\n";
    keep_window_open();
}

The code and exercise are from Programming Principles and Practice Using C++.

Gabriel
  • 763
  • 1
  • 10
  • 28
kevin
  • 147
  • 2
  • 11

2 Answers2

1

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.

Remy Lebeau
  • 555,201
  • 31
  • 458
  • 770
Chad
  • 18,706
  • 4
  • 46
  • 63
0

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');
}
Deqing
  • 14,098
  • 15
  • 84
  • 131