Sunday, July 12, 2009

How do I make it so this C++ program won't go into an infinite loop?

I'm not used to using character values in my loops. For some reason it goes a little while. It may not be infinite, I never waited long.





#include %26lt;iostream%26gt;


#include %26lt;fstream%26gt;





using namespace std;





char builder_name[35];


char choice;





void add_builder()


{





while(choice != 'N' || choice != 'n')


{





ofstream builders;


builders.open ("builders.txt", ios::app);





cout %26lt;%26lt; " Enter the name of a builder: ";


cin.get(builder_name, 35);


cin.ignore();





builders %26lt;%26lt; builder_name %26lt;%26lt; endl;





builders.close();





cout %26lt;%26lt; " Would you like to add another builder? (enter (Y) or (N): ";


cin %26gt;%26gt; choice;





};





}





int main ()


{





add_builder();





return 0;





}

How do I make it so this C++ program won't go into an infinite loop?
while(choice != 'N' || choice !='n')


In this line and (%26amp;%26amp;) should be used instead of or(||).


Because if or( || ) is used, atleast one condition will be true for any input (n or N). so loop will go infinite. Hence we should use and(%26amp;%26amp;) to make the loop to terminate for either of the input n or N.


Semicolon should not be used at end of while loop.
Reply:Change the line:


while(choice != 'N' || choice != 'n')


Into:


while(choice != 'N' %26amp;%26amp; choice != 'n')
Reply:Here's your problem - while(choice != 'N' || choice != 'n').


It's that ol' debbil double negative, in a different context. As long as choice isn't both N and n, it loops. If choice ==N, choice !=n is true and vice versa.


No comments:

Post a Comment