c++ While loops prints the couts twice -


in code, while loop prints cout twice when should print once, function's couts. don't understand why it's doing - supposed display

what do?

deposit

withdraw

cancel

but, displays twice.

while (yesno == 'y') {          cout << "what do?"             << endl             << endl;          menu();         getline(cin, bankchoice);          if (bankchoice == "withdraw")         {              withdrawtotal = withdraw(bankamount);             bankamount = withdrawtotal;             cout << "you have $"                 << bankamount                 << " in account."                 << endl;              cout << "would else?"                 << endl                 << "y/n: ";             cin >> yesno;          }          if (bankchoice == "deposit")         {              deposittotal = deposit(bankamount);             bankamount = deposittotal;             cout << "you have $"                 << bankamount                 << " in account."                 << endl;              cout << "would else?"                 << endl                 << "y/n: ";             cin >> yesno;         }           if (bankchoice == "cancel") {             return 0;         }      } 

that loop using. if additional code needed can post well, part causing issue. i've tried code without , works fine, i'd code loop until user enters 'n'.

you using both std::getline , operator>> read std::cin. operator>> not consume trailing newline, next call std::getline() read following newline , interpret empty line of text entered. run through loop, , go top, second prompt.

never use operator>> std::cin when intend read single line of text.

the following short example demonstrates point:

#include <iostream> #include <string>  int main() {     char c;     std::string l;      std::cin >> c;      std::cout << "a line of text please: ";      std::getline(std::cin, l); } 

run it, enter "y", , try figure out, yourself, why program terminates immediately.

once again: don't use operator>> read lines of text std::cin. recipe grief, , bugs.


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? -