How to keep_window_open() not working depending on inputs

前端 未结 2 1057
一向
一向 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::max(), '\n');
    }
    

提交回复
热议问题