如果语句在我的代码中不起作用

时间:2018-02-25 07:54:55

标签: c++ cppcheck

// a是一个整数,但如果在运行时按下字母表,代码会继续运行而不显示任何输入,而是显示无效输出并再次重复循环。

for (int j = 0; j <= 8; j++)
{
    if (j % 2 == 0){
        boad(arr);
        cout << "Player 1's turn " << endl << "Enter your position :";
        cin >> a;
        if (a == 0 || a == 1 || a == 2 || a == 3 || a == 4 || a == 5 || a == 6 || a == 7 || a == 8)
        {
            arr[a] = 'O';
            check(arr);
        }
        else 
        {

            cout << "invalid output";
            j = j - 1;
        }
    }
}

1 个答案:

答案 0 :(得分:1)

输入流不断尝试读取任何数字,如果失败,则设置ios::failbit位(这是一个标志,表示您的读取失败)。因此,您可以检查cin.fail(),这会检查failbit

    if (cin.fail()) {
        cout << "Invalid input\n";
    } else {
        cout << a << "\n";
    }

如果你这样做,当你输入一个字符时,它将保持写Invalid input,因为它仍然试图读取一个数字,并且你有一封信。

因此,要使流读取该行,然后从中提取数字,请使用std::getlinestd::stringstd::stringstream。像那样:

for(int i = 0; i < 4; i++) {
    std::string str;  // Create a string variable
    std::getline(cin, str); // Read a line, regardless of its components
    std::stringstream s(str); // Create a stream from this line
    s >> a; // Try to read an integer from this stream (which expresses the line)
    if (s.fail()) {
        std::cout << "Invalid input\n";
    } else {
        std::cout << a << "\n";
    }
}