int main() {
string inputName;
int age;
// Set exception mask for cin stream
cin.exceptions(ios::failbit);
cin >> inputName;
while (inputName != "-1") {
// FIXME: The following line will throw an ios_base::failure.
// Insert a try/catch statement to catch the exception.
// Clear cin's failbit to put cin in a useable state.
try
{
cin >> age;
cout << inputName << " " << (age + 1) << endl;
}
catch (ios_base::failure& excpt)
{
age = 0;
cout << inputName << " " << age << endl;
cin.clear(80, '\n');
}
inputName = "";
cin >> inputName;
}
return 0;
}
捕获异常后,我无法清除cin,甚至试图将变量设置为空字符串.我的程序在cin >> inputName上停止;在异常被捕获后,我认为cin.clear(80,'\n');重置cin并将其置于可用状态?
调试器告诉我,当我尝试将另一个字符串输入到inputName变量时,存在一个未处理的异常。任何帮助都是非常感谢的,谢谢。
发布于 2022-11-17 19:48:42
我不太明白你想修什么。无论如何,我只是解决了清洁cin的问题。
#include <iostream>
#include <limits>
using namespace std;
int main() {
string inputName;
int age;
// Set exception mask for cin stream
cin.exceptions(ios::failbit);
cout << "Input name: ";
cin >> inputName;
while (inputName != "-1") {
// FIXME: The following line will throw an ios_base::failure.
// Insert a try/catch statement to catch the exception.
// Clear cin's failbit to put cin in a useable state.
try {
cout << "Age: ";
cin >> age;
cout << inputName << " " << (age + 1) << endl;
break;
}
catch (ios_base::failure& except) {
cin.clear();
cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
}
}
return 0;
}
如您所见,我不向cin.clear()
传递任何参数,因为这个方法只是cin中的resets the state flags
。要清空cin buffer
,您必须使用cin.ignore()
传递的两个参数,第一个参数是size of the buffer
,在本例中,我使用cin.ignore()
来指定它,而第二个参数是告诉它end character
是什么。
https://stackoverflow.com/questions/74481147
复制相似问题