if语句只运行一个语句

时间:2016-07-31 21:07:31

标签: c++ if-statement while-loop std

我在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";

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

2 个答案:

答案 0 :(得分:2)

此代码:

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

答案 1 :(得分:1)

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