0

我正在创建自己的非常简单的程序,允许用户输入数值。目前代码工作得很好,但我需要一个验证 if else 语句。这就是我目前所拥有的;

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

}

我遇到的问题是,如果用户输入的不是数字,它返回的值是“偶数”。

希望各位小伙伴们帮帮忙!约翰

4

1 回答 1

4

不要将令牌提取 ( >>) 用于主解析。一旦提取失败,您的主要输入将处于未指定状态,这很糟糕。相反,逐行读取输入,然后处理每一行。

此外,永远不要忽略输入操作的结果。这只是一个简单的错误。

所以,把所有这些放在一起,你可以这样处理:

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

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

于 2012-11-18T22:19:20.877 回答