C++ cin.fail()问题

Jos*_*ore 3 c++ iostream cin

运行以下代码并输入数字时,它可以正常工作.但是当输入一个字母时,程序进入一个无限循环,显示"输入一个数字(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);
Run Code Online (Sandbox Code Playgroud)

小智 5

你需要使用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;
}
Run Code Online (Sandbox Code Playgroud)

这里仍然存在一个潜在的问题(在我的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);
}
Run Code Online (Sandbox Code Playgroud)

使用示例:

int n;
try {
  read_into(n, std::cin, "Enter a number: ");
}
catch (std::runtime_error& e) {
  //...
  raise;
}
cout << "Read " << n << '\n';
Run Code Online (Sandbox Code Playgroud)

为后代提取的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;
}
Run Code Online (Sandbox Code Playgroud)

如果你不习惯它,模板的东西有点混乱,但并不难:

  • std :: istream是一个typedefstd::basic_istream<char, std::char_traits<char> >
  • std :: wistream是一个typedefstd::basic_istream<wchar_t, std::char_traits<wchar_t> >
  • widen允许'\n'变得L'\n'合适
  • 此代码适用于常见的charwchar_t情况,但也适用于basic_istream的任何兼容实例
  • 它的编写被称为clearline(stream) 或者 stream >> clearline,与std :: endl,std :: wsstd :: boolalpha等其他操纵器相比较