输入验证需要输入两次

时间:2015-03-20 01:49:37

标签: c++ validation debugging input while-loop

我是编程新手,我在以下C ++程序的输入验证方面遇到了一些麻烦。

我的目标是阻止用户在给定域[100,999]内输入除整数之外的任何内容。

在输入第一个数字后程序似乎暂停。用户必须在执行代码cout << "you entered " << number << endl;之前输入第二个值。甚至没有考虑第一个输入。

问题似乎源于while循环。部分内容来自另一个在线论坛,所以我完全确定它的工作原理。但我知道这一点,没有循环,程序在第一次输入后执行而不是暂停(当然没有输入验证的好处)。

如何阻止用户输入两次号码?

    #include <iostream>
    #include <iomanip>
    #include <math.h>
    #include <limits>
    using namespace std;

    int main() {

        int number = 0;

        cout << "Please enter a whole number from 100 to 999:\n\n";
        cin >> number;


        //Check to see if entered value is a character 
        //or integer is within the given range

        while ((cin >> number).fail() || cin.peek() != '\n' || number > 999 || number < 100)
        {
            cin.clear();
            cin.ignore(numeric_limits<streamsize>::max(), '\n');

            cout << "Please enter an integer from 100 to 999:\n";
        }

        cout << "you entered " << number << endl;

        char q;
        cin >> q;

        return 0;
    }

1 个答案:

答案 0 :(得分:0)

您正在使用(cin >>number).fail(),再次呼叫cin>>。只需取出第一个cin,你就可以了。