0

私は、ユーザーが数値を入力できるようにする独自の非常に単純なプログラムを作成しています。現時点では、コードは問題なく機能しますが、ifelseステートメントの検証が必要です。これは私が現在持っているものです。

#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

>>一次解析にトークン抽出()を使用しないでください。抽出が失敗すると、プライマリ入力は不特定の状態のままになります。これはひどいことです。代わりに、入力を1行ずつ読み取り、各行を処理します。

また、入力操作の結果を無視しないでください。これは単なるエラーです。

したがって、これらすべてをまとめると、これを処理する方法は次のようになります。

#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)は、即時ブールコンテキストで表示されることに注意してください。

于 2012-11-18T22:19:20.877 に答える