Mr.Python Mr.Python - 4 months ago 9
C++ Question

only one statement under if statement being run

I made a program in C++ that ask for any integer input. The program crashes after only 2 iterations. The code is below:

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


I then tried doing this:

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


Which worked. Why does commenting out the second line, cause the program to run fine?

Answer

This code:

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

Is equivalent to:

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

Your problem becomes apparent, user_choice = right_answer is not executed only when counter == 10. Thus, move it inside the if () { ... } block:

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