输入的整数验证 [英] Integer validation for input

查看:119
本文介绍了输入的整数验证的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我尝试提示用户输入并进行验证。例如,我的程序必须接受3个用户输入。一旦它命中非整数,它将打印错误消息,并提示输入。下面是我的程序在运行时的外观:

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 :


输入数字:a

Enter number: a

错误的输入

输入数字:1

输入数字:b

输入错误

输入数字:2

输入数字:3

输入的数字是1,2,3

Numbers entered are 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循环,因为我要求用户输入。

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.

提前感谢。

推荐答案

当读取失败时,将 valid 设置为 false 条件在循环 false ,程序返回 input

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

    return (input);
}

这篇关于输入的整数验证的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆