输入的整数验证

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

输入数字:a

输入错误

输入数字:1

输入数字:b

输入错误

输入数字:2

输入数字:3

输入的数字为1,2,3

以下是我的代码:
double read_input()
{
    double input;
    bool valid = true;
    cout << "Enter number: " ;
    while(valid){
        cin >> input;
        if(cin.fail())
        {
            valid = false;
        }
    }
    return input;
}

我的主要方法:

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

当我的第一个输入不是整数时,程序会自动退出。它不会再次提示输入。我该如何修复它?或者我应该使用 do while 循环来请求用户输入。
提前感谢。

我们需要看更多的代码。你用调试器检查过吗?可能是崩溃了... - Karoly Horvath
在main方法中,我只写了double x = read_input(); double y = read_input(); double z = read_input(); 这样做错了吗? - user2424370
3个回答

9

当读取失败时,你需要将valid设置为false,这样在while循环中的条件就是false,程序会返回input(顺便提一下,这个变量并没有初始化)。

在再次使用缓冲区之前,你还需要清空它,可以像这样做:

#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);
}

当我在else语句中放置一个cout并输入非整数时,错误消息本身会不断循环。 - user2424370
我无法测试代码,但是Ideone有相同的输出结果,让我检查一下原因。 - Djon
@Carol,现在它可以工作了,我猜测是clearignore之间的顺序问题:http://ideone.com/fl4IMK - Djon
1
@Carol 在C和C++中,我总是初始化我的值(Java对此有所抱怨,所以现在我总是这样做),你不能在没有读取正确值的情况下退出函数,所以这是不必要的。Flush是为了确保标准输入缓冲区正确显示,我是这样学的,如果你愿意,可以将其删除。(endl是'\n' + flush,我想)。 - Djon
我重复使用了这个例子,但是当你对该函数进行多次调用并输入'20a5'之类的内容时,它仍然会导致轻微的问题。它可以正确地存储20,但是'a'部分会被下一个函数读取。虽然不是完美的解决方法,但在将输入切换为true后调用cin.clear和cin.ignore可以解决这个问题。当然,这一切都假设我的代码中没有错误。 - The_Redhawk
显示剩余2条评论

0

你的问题让我陷入了其他问题,例如在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;
}

0

问题出在 while 条件中。

bool valid = true;
while(valid){

你需要循环直到获得一个有效的输入,而不是无效的输入。这绝对不是你想要的!循环条件应该像这样:

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

这是您的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;
}

在你的主函数中,你需要请求尽可能多的双精度浮点数,例如:
int main()
{
    double d1 = read_input();
    double d2 = read_input();
    double d3 = read_input();

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

    return 0;
}

你可能还想要一个循环,在其中调用read_double()并将返回值保存在数组中。

好的,非常感谢。我在else语句中使用了cin.clear()和getline,现在它可以工作了。 - user2424370

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接