104

Google Code University の 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,'\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パラメータが必要な理由

4

4 に答える 4

120

cin.clear()エラー フラグをクリアしcin(将来の I/O 操作が正しく機能するようにするため)、cin.ignore(10000, '\n')次の改行にスキップします (非数値と同じ行にある他のものを無視して、別の解析エラーが発生しないようにするため)。 . 10000 文字までしかスキップしないため、コードは、ユーザーが非常に長い無効な行を入力しないことを前提としています。

于 2011-02-27T05:36:48.837 に答える
54

あなたが入力します

if (!(cin >> input_var))

cin からの入力を取得するときにエラーが発生した場合のステートメント。エラーが発生した場合、エラー フラグが設定され、以降の入力の試行は失敗します。それがあなたが必要な理由です

cin.clear();

エラーフラグを取り除きます。また、失敗した入力は、ある種のバッファーであると想定しています。入力を再度取得しようとすると、バッファ内の同じ入力が読み取られ、再び失敗します。それがあなたが必要な理由です

cin.ignore(10000,'\n');

バッファーから 10000 文字を取り出しますが、改行 (\n) に遭遇すると停止します。10000 は単なる一般的な大きな値です。

于 2011-02-27T05:44:44.490 に答える
1

cin.ignore(1000,'\n')バッファ内の前の文字をすべてクリアするために使用しcin.get()、「\ n」または1000 chars最初に一致したときに停止することを選択します。

于 2015-12-20T10:19:08.713 に答える