我的兄弟最近开始学习C ++。他告诉我在尝试验证简单程序中的输入时遇到的问题。他有一个文本菜单,用户输入整数choice
,如果他们输入无效的选项,将要求他们再次输入(do while循环)。但是,如果用户输入字符串而不是int,则代码将中断。
我阅读了stackoverflow上的各种问题,并告诉他按照以下方式重写代码:
#include<iostream>
using namespace std;
int main()
{
int a;
do
{
cout<<"\nEnter a number:"
cin>>a;
if(cin.fail())
{
//Clear the fail state.
cin.clear();
//Ignore the rest of the wrong user input, till the end of the line.
cin.ignore(std::numeric_limits<std::streamsize>::max(),\
'\n');
}
}while(true);
return 0;
}
虽然这种方法可以正常工作,但我还尝试了其他几个想法:
1. 使用try catch块。它没有起作用。我认为这是因为由于错误输入没有引发异常。 2. 我尝试了
if(! cin){//Do Something}
也不起作用。我还没弄清楚这个。
3. 第三,我尝试输入一个固定长度的字符串,然后解析它。我会使用atoi()。这符合标准并且可移植吗?或者应该编写自己的解析函数?
4. 如果编写一个使用cin的类,但动态执行此类错误检测,例如通过在运行时确定输入变量的类型,是否会有太多开销?这可能吗?我想知道做这种检查的最佳方法是什么,有哪些最佳实践?
我想补充一点,虽然我不是新手编写C++代码,但我是新手编写好的符合标准的代码。我正在努力消除不良做法并学习正确的方法。如果答案者能给出详细的解释,我将不胜感激。
编辑:我看到litb回答了我的先前编辑之一。我将在此处发布该代码以供参考。
#include<iostream>
using namespace std;
int main()
{
int a;
bool inputCompletionFlag = true;
do
{
cout<<"\nEnter a number:"
cin>>a;
if(cin.fail())
{
//Clear the fail state.
cin.clear();
//Ignore the rest of the wrong user input, till the end of the line.
cin.ignore(std::numeric_limits<std::streamsize>::max(),\
'\n');
}
else
{
inputCompletionFlag = false;
}
}while(!inputCompletionFlag);
return 0;
}
这段代码在输入类似于"1asdsdf"的情况下会失败。我不知道如何修复它,但litb发布了一个很好的答案。:)