c++ - 为什么我们会在读取输入后调用 cin.clear() 和 cin.ignore() ?

标签 c++ input iostream cin

Google Code University's C++ tutorial以前有这个代码:

// Description: Illustrate the use of cin to get input
// and how to recover from errors.

#include <iostream>
using namespace std;

int main()
{
  int input_var = 0;
  // Enter the do while loop and stay there until either
  // a non-numeric is entered, or -1 is entered.  Note that
  // cin will accept any integer, 4, 40, 400, etc.
  do {
    cout << "Enter a number (-1 = quit): ";
    // The following line accepts input from the keyboard into
    // variable input_var.
    // cin returns false if an input operation fails, that is, if
    // something other than an int (the type of input_var) is entered.
    if (!(cin >> input_var)) {
      cout << "Please enter numbers only." << endl;
      cin.clear();
      cin.ignore(10000,'\n');
    }
    if (input_var != -1) {
      cout << "You entered " << input_var << endl;
    }
  }
  while (input_var != -1);
  cout << "All done." << endl;

  return 0;
}

cin.clear()cin.ignore()的意义是什么?为什么需要 10000\n 参数?

最佳答案

cin.clear() 清除 cin 上的错误标志(以便将来的 I/O 操作正常工作),然后 cin.ignore (10000, '\n') 跳到下一个换行符(忽略与非数字在同一行的任何其他内容,以免导致另一个解析失败)。它最多只能跳过 10000 个字符,因此代码假设用户不会输入很长的无效行。

关于c++ - 为什么我们会在读取输入后调用 cin.clear() 和 cin.ignore() ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5131647/

相关文章:

c++ - Tensorflow load graph c++ 示例中包含哪些 header ?

c++ - 为什么我们需要一个单位 vector (换句话说,为什么我们需要对 vector 进行归一化)?

c++ - C++ 中 func() 和 (*this).func() 的区别

c++ - 基于 partial_index_search 的结果 boost multi_index_container 部分索引搜索

HTML - 表单,两个文本输入。必需的属性。如何,用户必须在两个字段中的任何一个中输入字符串才能提交?

Javascript:如何返回具有多组输入的函数总和

C++ 验证 - 截断设置为下一个输入

javascript - 如何在 angularjs 2 中的 @Input 参数上执行函数?

C++:继承 std::basic_streambuf 的问题

iostream - Julia:有一个包含宏 @printf 的函数 f(),如何访问 f() 之外的输出?