Sunday, July 12, 2009

Why does this c++ program go into an infinite loop?

This program keeps going into an infinite loop for some reason. When I delete everything from ofstream builders; to builders.close(); cin.ignore(); it doesn't go into the infinite loop. So the eroor is somewhere in there.





#include %26lt;iostream%26gt;


#include %26lt;fstream%26gt;





using namespace std;





char builder_name[35];


char choice;





void add_builder()


{





while(choice != 'N' %26amp;%26amp; choice != 'n')


{





// error is somewhere between here





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();


cin.ignore();





// and here





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


cin %26gt;%26gt; choice;





}





}





int main ()


{





add_builder();





return 0;





}

Why does this c++ program go into an infinite loop?
Move the 2nd cin.ignore() to after cin %26gt;%26gt; choice;





In response to the other answerer, your logic in the while loop is fine.





(choice != 'N' %26amp;%26amp; choice != 'n')





If choice is Q, y or anything then it is both != 'N' and !='n' (true %26amp;%26amp; true : true)





If choice is N then the conditions is true %26amp;%26amp; false which is false, and the condition fails, ending the loop.





If the choice is n, then the condition is false %26amp;%26amp; true which is false, and the condition fails, ending the loop.





I think the third answerer is confusing "%26amp;%26amp; and" with "|| or"





while(choice != 'N' || choice != 'n') (this will be an infinite loop)
Reply:The while loop never breaks.


and found the mistake 1st U said


while(choice != 'N' %26amp;%26amp; choice != 'n')


This is impossible instead try this


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


2nd


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


cin %26gt;%26gt; choice;


\\write this


if(choice == 'N' || choice == 'n'){


break();


}else{


\\name of that Function or declartion
Reply:because you put "return 0 ;" that makes it return to the begining of the code. and the semi colon makes it a command. at least i think thats what it is.


No comments:

Post a Comment