数字输入的C ++输入验证 [英] C++ input validation for numeric input

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

问题描述

我创建了自己的非常简单的程序,允许用户输入数值。目前代码工作正常,但我需要一个验证if语句。这是我现在的时间;

I'm creating my own very simple program that allows the user to input a numeric value. At the moment the code works just fine, but I need a validation if else statement. This is what I have at the moment;

#include <iostream>
#include <string>

using namespace std;

int main()
{

    unsigned __int64 input = 0;
    char str[] = "qwertyuiopasdfghjklzxcvbnm[]{};'#:@~,./<>?|!£$%^&*()";

    cout << "Insert a number" << endl;
    cin >> input;

    if (input % 2 == 0) 
    {
        cout << "Even!" << endl;
    }
    else 
    {
        if (input% 2 == 1)
        {
            cout << "Odd" << endl;
            cout << "Lets make it even shall we? " << "Your new number is... " << input + 1 << endl;
        }
        else if (isdigit(str[0]))
        {
            cout << "That isn't a number!" << endl;
        }
    }

    system("pause");
    return 0;

}

我遇到的问题是,如果用户输入任何东西这不是一个数字,它返回的值是Even。

The issue I am having is that if the user inputs anything that isn't a number, the value it returns is "Even".

我希望你们和女孩可以帮助!
John

I hope you guys and girls can help! John

推荐答案

不要使用令牌提取(>> )用于主解析。一旦提取失败,您的主要输入将处于未指定的状态,这是可怕的。

Don't use token extraction (>>) for primary parsing. Once the extraction fails, your primary input is left in an unspecified state, which is terrible. Instead, read the input line by line and then process each line.

此外,从不忽略输入操作的结果。

Also, never ignore the result of an input operation. That's just a flat error.

因此,将所有这些组合在一起,这里是如何处理这个:

So, putting all this together, here's how you could handle this:

#include <iostream>
#include <sstream>
#include <string>

int main()
{
    for (std::string line; std::cout << "Input: " && std::getline(std::cin, line); )
    {
        std::cout << "We're parsing your line '" << line << "'\n";

        int n;
        std::istringstream iss(line);

        if (iss >> n >> std::ws && iss.get() == EOF)
        {
            std::cout << "It was a number: " << n << "\n";
        }
        else if (line.empty())
        {
            std::cout << "You didn't say anything!\n";
        }
        else
        {
            std::cout << "We could not parse '" << line << "' as a number.\n";
        }
    }

    std::cout << "Goodbye!\n";
}

请注意,所有输入操作(即> ; getline )出现在立即布尔上下文中!

Note that all input operations (namely >> and getline) appear in immediate boolean contexts!

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

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