我改编了 Bjarne Stroustrup 的 Programming: Principles and Practice in C++ 中的代码,试图检查给定的输入是否有效:
#include <iostream>
using namespace std;
int main()
{
cout << "Please enter your first name and age: ";
string first_name = "???";
int age = -1;
cin >> first_name >> age;
while (!cin) {
cin.clear();
cout << "Sorry, can you enter that again? ";
cin >> first_name >> age;
}
cout << "Hello, "<<first_name<<"! (age "<<age<<")\n";
return 0;
}
这按预期工作,除了单词"Sorry, can you enter that again? "
被打印两次,一次在第二次输入之前和一次之后。
有谁知道为什么会发生这种情况?谢谢。