我想询问用户输入,我用 cin 得到的输入是这样的
void AskForGroundstate() {
cout << "Please enter an groundstate potential value in Volt:" << endl;
if (!(cin >> _VGroundstate)) {
cin.clear();
cin.ignore();
cout << "Groundstate potential not valid." << endl;
AskForGroundstate();
}
}
_VGroundstate 是 double 型,因此如果用户输入不带数字的字符串,则应再次要求他提供更好的输入。但问题是,当输入例如“AA”时,程序会执行 AskForGroundstate 两次,“AAA”执行三次,依此类推。我是否使用了clear错误?
最佳答案
问题是 cin.ignore()
丢弃了一个字符;您想要将所有字符放到行尾:
cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
这可确保在最终用户再次提示输入之前删除所有无效输入。
关于c++ - 捕获 cin 异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38200600/