[英]C++ cin.fail() question
运行以下代码并输入数字时,它可以正常工作。 但是当输入一个字母时,程序进入一个无限循环,显示“输入一个数字(0退出):cin失败。”
我的意图是处理cin失败案例并再次提示用户。
int number;
do{
cout << "Enter a number (0 to exit): ";
cin >> number;
if(cin.fail()){
cout << "cin failed." << endl;
cin.clear();
}else{
cout << "cin succeeded, " << number << " entered." << endl;
}
}while(number != 0);
你需要使用cin.ignore清除cin中的行,除了清除流状态(这是cin.clear所做的)。
我有几个实用程序函数,以使这更容易(你会特别感兴趣的clearline ,它清除流状态和当前行)和几乎所有你想要的确切示例。
您的代码,或多或少,使用我的clearline :
#include "clinput.hpp" // move my file to a location it can be used from
int main() {
using namespace std;
while (true) {
cout << "Enter a number (0 to exit): ";
int number;
if (cin >> number) {
cout << "Read " << number << '\n';
if (number == 0) {
break;
}
}
else {
if (cin.eof()) { // tested only *after* failed state
cerr << "Input failed due to EOF, exiting.\n";
return 1;
}
cerr << "Input failed, try again.\n";
clearline(cin); // "cin >> clearline" is identical
}
}
return 0;
}
这里仍然存在一个潜在的问题(在我的clinput_loop.cpp中使用blankline修复),在缓冲区中留下输入,这将使后来的IO搞砸(参见示例会话中的“42 abc”)。 将上面的代码提取到一个单独的,自包含的函数中留给读者练习,但这是一个骨架:
template<class Type, class Ch, class ChTr>
Type read(std::basic_istream<Ch,ChTr>& stream, Ch const* prompt) {
Type value;
// *try input here*
if (could_not_get_input or more_of_line_left) {
throw std::runtime_error("...");
}
return value;
}
template<class Type, class Ch, class ChTr>
void read_into(
Type& value,
std::basic_istream<Ch,ChTr>& stream,
Ch const* prompt
) {
value = read<Type>(stream, prompt);
}
使用示例:
int n;
try {
read_into(n, std::cin, "Enter a number: ");
}
catch (std::runtime_error& e) {
//...
raise;
}
cout << "Read " << n << '\n';
为后代提取的clearline函数,以防上面的链接中断(并稍微更改为自包含):
#include <istream>
#include <limits>
template<class C, class T>
std::basic_istream<C,T>& clearline(std::basic_istream<C,T>& s) {
s.clear();
s.ignore(std::numeric_limits<std::streamsize>::max(), s.widen('\n'))
return s;
}
如果你不习惯它,模板的东西有点混乱,但并不难:
std::basic_istream<char, std::char_traits<char> >
的typedef std::basic_istream<char, std::char_traits<char> >
std::basic_istream<wchar_t, std::char_traits<wchar_t> >
'\\n'
在适当时变为L'\\n'
clearline(stream)
或 stream >> clearline
,与其他操纵stream >> clearline
如std :: endl , std :: ws或std :: boolalpha相比较 这可能是你打算做的:
#include <iostream>
using namespace std;
int main ()
{
int i;
do {
if (cin.fail())
{
cin.ignore(255);
cin.clear();
}
cout << "Please enter an integer value: ";
cin >> i;
} while ( cin.fail() );
cout << "The value you entered is " << i;
return 0;
}
这是cin.fail()的简单示例。它将处理输入,直到提供有效的整数值
#include <iostream>
using namespace std;
int main()
{
int j;
int i;
i = 0;
while (1) {
i++;
cin >> j;
if (cin.fail()) return 0;
cout << "Integer " << i << ": " << j << endl;
}
}
输入:
42 51 85你好85
输出:
整数1:42
整数2:51
整数3:85
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.