Thursday, July 9, 2009

How do you stop C++ loops from going on forever in while statements?

I hope this does not prove to be too difficult.


I have a problem. I am trying to make a C++ program that functions as a quiz in which a student would choose one of four choices as an answer, and, if the answer is given incorrect, the program would continue to ask the question until the correct answer is chosen, but each different question selected, it gives the student a hint about the question.





This is what I have right now as a test, please help fixing it or telling me what is wrong with it.





#include %26lt;iostream%26gt;





int main()


{


int secretAnser, userAnswer;





secretNum = 5;


cout %26lt;%26lt; "The Lecompton Constitution was created in which state?: ";


cin %26gt;%26gt; userAnswer;





while (userAnser != secretAnswer)


{


cout %26lt;%26lt; "Wrong try again." break;





}





cout %26lt;%26lt; "You finally got it right" %26lt;%26lt; endl;


cout %26lt;%26lt; "Thanks" %26lt;%26lt; endl;





if (userAnser == secretAnswer)


{cout %26lt;%26lt; "dang kid, you physic";}


else


{cout %26lt;%26lt; "Your way off." %26lt;%26lt; endl;


cout %26lt;%26lt; "Good Job." %26lt;%26lt; endl;


}








return 0;


}

How do you stop C++ loops from going on forever in while statements?
You should input student answer in the while loop but your while loop should be infinity.


So, you can try it...





while (1) //the loop will do forever


{


cout %26lt;%26lt; "The Lecompton Constitution was created in which state?: ";


cin %26gt;%26gt; userAnswer;





if (userAnser != secretAnswer)


break;


else


cout %26lt;%26lt; "Wrong try again%26lt;%26lt;endl;





}





at end, your loop are going until user chosen correct answer





Enjoy
Reply:there's nothing wrong with your syntax.. maybe you should try another syntax (equivalent), maybe its not just compatible with your pc. even you input another "useranser" it wouldn't work because you must need it to debug(compile it first)before hitting "run"
Reply:you also never set secretAnswer to anything, unless secretNum was a typo, and should have been secretAnswer.
Reply:You spelt 'userAnswer' wrong inside your while statement. If the value never changes, it's going to keep displaying the same question.





Try this:





while (userAnswer != secretAnswer)


{





cout %26lt;%26lt; "Wrong try again." break;


cin %26gt;%26gt; userAnswer;





}
Reply:break out of the loop


No comments:

Post a Comment