c++ - 使用 cin.fail 进行 CIN 验证

标签 c++ validation cin

我正在开发一个小程序,它使用 std::cin 一个接一个地请求 4 个整数。我正在使用一个函数来请求整数,并将允许的最大值作为参数传递。要检查值是否为整数,我使用 std::cin.fail。调用函数的代码如下所示。

    cout << "Specify source number (1 - 1024)\n";
    source = validate(1024);
    cout << "Specify destination number (1 - 1024)\n";         // For all except data, the value is equal to the value returned by the validate function
    destination = validate(1024);                              // The maximum possible value is passed in as an argument in each of the cases.
    cout << "Specify type number (1 - 10)\n";                  // User  is prompted to enter the desired values.
    type = validate(10);
    cout << "Source port number (1 - 1024)\n";
    port = validate(1024);

验证函数代码如下所示。

int validate(int max) {

int value;                                  // Initialise variable to hold the value.

for (;;) {                                  // Loop forever until correct input is entered.
    cin >> value;

    if (cin.fail()) {                // If cin fails to receive a value matching the declared data type.
        cout << "Characters are not permitted.\n";          // Notify the user of error.
        cin.clear();                    // Clear the error flag within cin.
        cin.ignore(10000,'\n');         // Ignore the newline character in the buffer to prevent an infinite loop.
        }
    else if (value > max || value == 0) {
        cout << "The value you have entered is not valid, please enter a number between 1 and " << max << "\n";
        cin.clear();                    // Clear the error flag within cin.
        cin.ignore(10000, '\n');        // Ignore the newline character in the buffer to prevent an infinite loop.
    }
    else
        break;
    }
return value;                           // Return the validated value.
}

如果用户只输入一个整数或一个字母,它就可以正常工作,它会按预期进行验证,我遇到的问题是,如果用户输入例如 34d22p 。我收到错误消息说 characters are not permitted 但随后它退出该函数并移至下一个请求。

尝试重新排列,但似乎无法解决问题。 非常感谢任何帮助

最佳答案

你想要做的是忽略该行的其余部分,即使你成功了:

int validate(int max) {

int value;                                  // Initialise variable to hold the value.

for (;;) {                                  // Loop forever until correct input is entered.
    cin >> value;

    if (cin.fail()) {                // If cin fails to receive a value matching the declared data type.
        cout << "Characters are not permitted.\n";          // Notify the user of error.
        cin.clear();                    // Clear the error flag within cin.
        cin.ignore(10000,'\n');         // Ignore the newline character in the buffer to prevent an infinite loop.
        }
    else if (value > max || value == 0) {
        cout << "The value you have entered is not valid, please enter a number between 1 and " << max << "\n";
        cin.clear();                    // Clear the error flag within cin.
        cin.ignore(10000, '\n');        // Ignore the newline character in the buffer to prevent an infinite loop.
    }
    else {
        cin.ignore(10000, '\n');        // Ignore the newline character in            
        break;
    }
}
return value;                           // Return the validated value.
}

如果你觉得这太重复了,你可以这样做:

struct ignore_till_eol {
  ignore_till_eol(std::istream& cin): input(cin) {}
  ~ignore_till_eol() { input.clear(); input.ignore(std::numeric_limits<std::streamsize>::max(), '\n'); }
  std::istream& input;
};

int validate(int max_value) {
  for(;;) {
    ignore_till_eol ignore(cin);
    int v;
    if( cin >> v && 0 < v && v <= max_value ) return v;
    if( cin )
        cout << "Value is invalid, must be between 1 and " << max_value << "\n";
    else
        cout << "Invalid characters in input\n";
  }
}

int validate(int max_value) {
  for(;;) {
    ignore_till_eol ignore(cin);
    int v;
    if( !(cin >> v) )
        cout << "Invalid characters in input\n";
    else if( 0 < v && v <= max_value )
        return v;
    else
        cout << "Value is invalid, must be between 1 and " << max_value << "\n";
  }
}

关于c++ - 使用 cin.fail 进行 CIN 验证,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23289927/

相关文章:

c++ - malloc() 和 malloc_consolidate() 中的段错误

javascript - Selectize.js 和 jQuery 验证

validation - 如何制作 CheckBoxList 验证器

c++ - 为什么在 "getline"之后使用 "cin"时需要 cin.ignore() 而在多次使用 "cin"时不需要?

c++ - 为什么第二个 'cin >>' 不会被处理?

c++ - 如何将字符串更改为 QString?

c++ - 三次贝塞尔曲线是否完全包含在其控制点的边界框内?

c++ - fftw C++ 来自幅度和相位数组的逆二维 FFT

javascript - 如何禁用对隐藏控件的验证

c++ - 用户输入在循环中不断询问 C++