如何在c++中正确使用cin.fail()
How to use cin.fail() in c++ properly
我正在写一个程序,我从用户那里得到一个整数输入与cin>>iUserSel;
。如果用户输入一个字母,程序就进入无限循环。我试图用下面的代码来防止这种情况,但是程序进入了一个无限循环,并打印出"错误!输入#!"。我如何修复我的程序?
cin>>iUserSel;
while (iValid == 1)
{
if (cin.fail())
{
cin.ignore();
cout<<"Wrong! Enter a #!"<<endl;
cin>>iUserSel;
}//closes if
else
iValid = 0;
}//closes while
我在正确使用cin.fail()和c++ cin.fail()问题中找到了一些关于这方面的信息,但我不知道如何使用它们来解决我的问题
当cin
失败时,需要清除错误标志。否则,后续的输入操作将是非操作。
清除错误标志,需要调用cin.clear()
。
你的代码将变成:
cin >> iUserSel;
while (iValid == 1)
{
if (cin.fail())
{
cin.clear(); // clears error flags
cin.ignore();
cout << "Wrong! Enter a #!" << endl;
cin >> iUserSel;
}//closes if
else
iValid = 0;
}//closes while
我还建议你修改
cin.ignore();
cin.ignore(numeric_limits<streamsize>::max(), 'n');
如果用户输入多个字母
您遇到的问题是您没有从流中清除 failbit
。这是通过clear
函数完成的。
在一些相关的注意事项上,您实际上根本不需要使用
fail
函数,而是依赖于输入操作符函数返回流的事实,并且流可以在布尔条件下使用,然后您可以做如下(未经测试)代码:
while (!(std::cin >> iUserSel))
{
// Clear errors (like the failbit flag)
std::cin.clear();
// Throw away the rest of the line
std::cin.ignore(std::numeric_limits<std::streamsize>::max(), 'n');
std::cout << "Wrong input, please enter a number: ";
}
我的建议是:
// Read the data and check whether read was successful.
// If read was successful, break out of the loop.
// Otherwise, enter the loop.
while ( !(cin >> iUserSel) )
{
// If we have reached EOF, break of the loop or exit.
if ( cin.eof() )
{
// exit(0); ????
break;
}
// Clear the error state of the stream.
cin.clear();
// Ignore rest of the line.
cin.ignore(std::numeric_limits<std::streamsize>::max(), 'n');
// Ask more fresh input.
cout << "Wrong! Enter a #!" << endl;
}
相关文章:
- Problems with std::cin.fail()
- 了解 cin.fail() 和 cin.clear语言 - Vector 追加程序
- cin.fail() not returning true
- cin.fail 在输入数字和字母时不起作用
- 我如何检查CIN.FAIL(),但仍使用Ctrl D到达文档的结尾
- CIN.FAIL无法按预期工作
- 如何使用CIN.FAIL()杀死程序
- 有没有办法将cin.fail和cin.clear翻译成C编程语言
- 如何在cin.fail()中求解循环
- C++ cin.fail() while loop
- 为什么 cin.fail() 在输入数字后跟字符时不返回 false?
- 输入验证用于选择用字符的项目,通过CIN.FAIL遇到错误
- 使用 cin::fail() 从 stdin 进行无限循环读取
- 检查 cin.fail() 中字符串变量时出错C++
- 使用 cin.fail() 表示整数与地板
- 我的程序中 cin.fail() 的 C++ 问题
- C++ 使用 cin.fail(), cin.clear() ---我有一个无限循环,不知道为什么
- 使用cin.fail()时存在Ininite循环
- 使用cin.fail()的正确方法
- 如何在c++中正确使用cin.fail()