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

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

问题描述

Google Code University的C ++教程用于具有以下代码:

  //说明:说明使用cin获取输入
//以及如何恢复从错误。

#include< iostream>
using namespace std;

int main()
{
int input_var = 0;
//输入do while循环并保持到
//输入一个非数字或输入-1。注意
// cin将接受任何整数4,40,400等。
do {
cout<< 输入数字(-1 =退出):;
//以下行接受来自键盘的输入到
// variable input_var。
//如果输入操作失败,cin返回false,也就是说,如果
//输入int以外的东西(input_var的类型)。
if(!(cin>> input_var)){
cout< 请只输入数字。 << endl;
cin.clear();
cin.ignore(10000,'\\\
');
}
if(input_var!= -1){
cout< 您输入了<< input_var<< endl;
}
}
while(input_var!= -1);
cout<< 全做完了。 << endl;

return 0;
}

cin.clear cin.ignore()?为什么需要 10000 \\\
参数?

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


Google Code University's C++ tutorial used to have this code:

// 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;
}

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

解决方案

The cin.clear() clears the error flag on cin (so that future I/O operations will work correctly), and then cin.ignore(10000, '\n') 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天全站免登陆