switch case infinite loop bug in c++ -


this question has answer here:

i working on menu driven program output adjacency matrix homework assignment. when put character in input after call of other 4 cases loop runs infinitely , can't figure out why.

this happens regardless if have case 5 active.

but if enter character first input closes intended.

i stepped through debugger , seems if character entered takes input 4 , never takes input keeps printing array on , over.

can explain wrong function? have function here because entire program 300 lines not counting comments. through testing i've narrowed bug down specific function others meant to.

    void menu(char graph[][8]) {     bool run = true;     while (run == true)     {         int menuchoice;         cout << "welcome menu" << endl;         cout << "pick 1 of following" << endl;         cout << "1. add connection" << endl;         cout << "2. delete connection " << endl;         cout << "3. show total number of connections " << endl;         cout << "4. show matrix " << endl;         cout << " 5. exit" << endl;         cout << "selection : ";         cin >> menuchoice;         switch (menuchoice)         {         case 1: addconnection(graph);             break;         case 2: deleteconnection(graph);             break;         case 3: showconnection(graph);             break;         case 4: showmatrix(graph);             break;         /*case 5:             cout << "exiting ...\n";             run = false;             break;*/         default:             cout << "improper input " << endl; // reason flies infinite when character entered.             cout << "exiting ...\n";             run = false;             break;          }     } } 

this textbook case why operator>> should never handle interactive line-oriented input.

if intent enter line of text, that's std::getline() for.

this code uses operator>> on int.

if character entered takes input 4

no, doesn't. operator>> conversion fails. menuchoice uninitialized, contains random junk. may '4', may 'x', may unprintable character. sky's limit.

but more important, std::cin has has failed bit set, , further attempts read std::cin fail, until stream status clear()ed. code never it, , keeps looping on , on again, vainly attempting operator>> next character, which, of course, not since stream in failed state. , since code doesn't check status of input stream, has no idea what's going on.

do not use operator>> read std::cin. if want read line of text, use std::getline(), , parse whatever read using independent std::istringstream.


Comments

Popular posts from this blog

java - nested exception is org.hibernate.exception.SQLGrammarException: could not extract ResultSet Hibernate+SpringMVC -

sql - Postgresql tables exists, but getting "relation does not exist" when querying -

asp.net mvc - breakpoint on javascript in CSHTML? -