Mr.Python Mr.Python - 3 months ago 8
C++ Question

When two statements are put under a if statement only one executes

I made a program in C++ that ask for any integer input other than 5, and keeps asking until you enter 5. It then outputs a statement. If the user has not entered 5 after 10 iterations of the while loop then the user wins. However, after trying to check if the loop had run 10 times in the while loop using an if statment and a

std::cout
command, The program crashes after only 2 iterations. I am clueless to why this is. Code below:

#include<iostream>

int main()
{
int user_choice;
int right_answer = 5;
int counter = 0;

std::cout <<"Please enter any number other than five: ";
std::cin >> user_choice;

while(user_choice != right_answer)
{
counter += 1;
std::cout <<"Please enter any number other than five: ";
std::cin >> user_choice;

if (user_choice == 5)
user_choice = right_answer;

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

return 0;
}


The funny thing is though, is that when i remove the
std::cout
command under the second if statement, the program runs 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;
}
Comments