C++ 输入的整数验证

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/16934183/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-27 20:46:08  来源:igfitidea点击:

Integer validation for input

c++validationwhile-loop

提问by Djon

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 :

我试图提示用户输入并进行验证。例如,我的程序必须接受 3 个用户输入。一旦遇到非整数,它会打印错误信息并再次提示输入。这是我的程序在运行时的样子:

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

输入号码:a

输入错误

输入数字:1

输入号码:b

输入错误

输入数字:2

输入数字:3

输入的数字是 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.

当我的第一个输入是非整数时,程序会自行退出。它不会再次要求提示。我怎么能修好呢?或者我应该使用 do while 循环,因为我要求用户输入。

Thanks in advance.

提前致谢。

回答by Djon

When the reading fails, you set validto false, so the condition in the whileloop is falseand the program returns input(which is not initialized, by the way).

当读取失败时,您设置validfalse,因此while循环中的条件是false并且程序返回input(顺便说一下,它没有被初始化)。

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(),'\n');
            cout << "Invalid input; please re-enter." << endl;
        }
    } while (!valid);

    return (input);
}

回答by Manoj Awasthi

Your question did get myself into other issues like clearing the cin on fail() --

你的问题确实让我陷入了其他问题,比如在 fail() 上清除 cin——

double read_input()
{
double input;
int count = 0; 
bool valid = true;
while(count != 3) {
    cout << "Enter number: " ;
    //cin.ignore(); 
    cin >> input; 
    if(cin.fail())
    {
        cout << "Wrong Input" <<endl;
        cin.clear(); 
        cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n'); 
    }
    else 
            count++;
}
return input;
}

回答by A4L

The problem is in the while condition

问题出在 while 条件下

bool valid = true;
while(valid){

You loop until you get a non valid input, this absolutly not what you want! loop condition should be like this

你循环直到你得到一个无效的输入,这绝对不是你想要的!循环条件应该是这样的

bool valid = false;
while(! valid){ // repeat as long as the input is not valid

Here is a modified version of your read_double

这是你的修改版 read_double

double read_input()
{
    double input;
    bool valid = false;
    while(! valid){ // repeat as long as the input is not valid
        cout << "Enter number: " ;
        cin >> input;
        if(cin.fail())
        {
            cout << "Wrong input" << endl;

            // clear error flags
            cin.clear(); 
            // Wrong input remains on the stream, so you need to get rid of it
            cin.ignore(INT_MAX, '\n');
        }
        else 
        {
            valid = true;
        }
    }
    return input;
}

And in your main you need to ask for as may doubles as you want, for example

例如,在您的主要要求中,您需要尽可能多地加倍

int main()
{
    double d1 = read_input();
    double d2 = read_input();
    double d3 = read_input();

    cout << "Numbers entered are: " << d1 << ", " << d2 << ", " << d3 << endl;

    return 0;
}

You may also want to have a loop where you call read_double()and save the returned values in an array.

您可能还希望有一个循环,您可以在其中调用read_double()返回值并将其保存在数组中。