if 语句下只有一个语句是 运行

only one statement under if statement being run

我用 C++ 编写了一个程序,要求输入任何整数。该程序仅在 2 次迭代后崩溃。代码如下:

#include<iostream>

int main()
{   
    int user_choice;
    std::cout <<"Please enter any number other than five: ";
    std::cin >> user_choice;

    while(user_choice != 5)
    {
        std::cout <<"Please enter any number other than five: ";
        std::cin >> user_choice;
        if(user_choice == 5)
            std::cout << "Program Crash";
            break;
    }
    std::cout << "I told you not to enter 5!";
    return 0;
}

然后我尝试这样做:

if(user_choice == 5)
    std::cout << "Program Crash";
    //std::cout << "Shutting Down";

哪个有效。为什么注释掉第二行会使程序 运行 正常?

C++ 不尊重缩进;所以当你写:

if (counter == 10)
    std::cout << "Wow you still have not entered 5. You win!";
    user_choice = right_answer; 

编译器看到:

if (counter == 10)
    std::cout << "Wow you still have not entered 5. You win!";
user_choice = right_answer; 

要将两个语句都放在 if 下,您需要大括号:

if (counter == 10) {
    std::cout << "Wow you still have not entered 5. You win!";
    user_choice = right_answer; 
}

此代码:

if (counter == 10)
    std::cout << "Wow you still have not entered 5. You win!";
    user_choice = right_answer;

相当于:

if (counter == 10)
{
    std::cout << "Wow you still have not entered 5. You win!";
}
user_choice = right_answer;

你的问题就很明显了,user_choice = right_answer只有在counter == 10时才不执行。因此,将其移动到 if () { ... } 块内:

if (counter == 10)
{
    std::cout << "Wow you still have not entered 5. You win!";
    user_choice = right_answer;
}