【问题标题】:If statement is not working in my code [duplicate]如果语句在我的代码中不起作用[重复]
【发布时间】:2018-02-25 07:54:54
【问题描述】:

//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;
        }
    }
}

【问题讨论】:

  • 不是一个真正的解决方案,但可能希望将其更改为 if(0 &lt;= a &amp;&amp; a &lt; 9)
  • 那是因为当你按下字母时,它对应的 ASCII 码位于变量 'a' 中,(a-z => 65-90, A-Z => 97-122),因此跳过了 if 块。
  • @JeffinManuel 他在问,为什么在给出无效输出时 else 块没有运行。
  • 我不确定您实际上在问什么,尽管我认为 Felix 猜得不错。请展示你的输出,解释你不喜欢它的什么地方,并可能展示你想要的输出。
  • @Yunnosch 当我按下一个字母时它会完成它的循环而不要求输入并关闭。

标签: c++ cppcheck


【解决方案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";
    }
}

【讨论】:

    猜你喜欢
    • 2015-05-09
    • 2013-05-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-07-30
    • 1970-01-01
    • 1970-01-01
    • 2023-01-23
    相关资源
    最近更新 更多