Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
110 views
in Technique[技术] by (71.8m points)

c++ - Integer validation for input

I tried to prompt user for input and do the validation. For example, my program must take in 3 user inputs. Once it hits non-integer, it will print error message and prompt for input again. Here is how my program going to be look like when running :

Enter number: a

Wrong input

Enter number: 1

Enter number: b

Wrong input

Enter number: 2

Enter number: 3

Numbers entered are 1,2,3

And here is my code:

double read_input()
{
    double input;
    bool valid = true;
    cout << "Enter number: " ;
    while(valid){
        cin >> input;
        if(cin.fail())
        {
            valid = false;
        }
    }
    return input;
}

My main method:

int main()
{
double x = read_input();
double y = read_input();
double z = read_input();
}

When my first input is non-integer, the program just exits by itself. It does not ask for prompting again. How could I fixed it? Or am I supposed to use a do while loop since I asking for user input.

Thanks in advance.

Question&Answers:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

When the reading fails, you set valid to false, so the condition in the while loop is false and the program returns input (which is not initialized, by the way).

You also have to empty the buffer before using it again, something like:

#include <iostream>
#include <limits>

using namespace std;

double read_input()
{
    double input = -1;
    bool valid= false;
    do
    {
        cout << "Enter a number: " << flush;
        cin >> input;
        if (cin.good())
        {
            //everything went well, we'll get out of the loop and return the value
            valid = true;
        }
        else
        {
            //something went wrong, we reset the buffer's state to good
            cin.clear();
            //and empty it
            cin.ignore(numeric_limits<streamsize>::max(),'
');
            cout << "Invalid input; please re-enter." << endl;
        }
    } while (!valid);

    return (input);
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...