How to keep_window_open() not working depending on inputs

前端 未结 2 1056
一向
一向 2021-01-26 17:19

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

相关标签:
2条回答
  • 2021-01-26 17:29

    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');
    }
    
    0 讨论(0)
  • 2021-01-26 17:36

    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.

    0 讨论(0)
提交回复
热议问题