为什么我们会在读取输入后调用 cin.clear() 和 cin.ignore() ? [英] Why would we call cin.clear() and cin.ignore() after reading input?

查看:23
本文介绍了为什么我们会在读取输入后调用 cin.clear() 和 cin.ignore() ?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Google 代码大学的 C++ 教程 曾经有这个代码:

// 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,'
');
    }
    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 参数?

What is the significance of cin.clear() and cin.ignore()? Why are the 10000 and parameters necessary?

推荐答案

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

The cin.clear() clears the error flag on cin (so that future I/O operations will work correctly), and then cin.ignore(10000, ' ') skips to the next newline (to ignore anything else on the same line as the non-number so that it does not cause another parse failure). It will only skip up to 10000 characters, so the code is assuming the user will not put in a very long, invalid line.

这篇关于为什么我们会在读取输入后调用 cin.clear() 和 cin.ignore() ?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆