How to keep_window_open() not working depending on inputs

前端 未结 2 1058
一向
一向 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: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.

提交回复
热议问题