c++ - I Can't Figure Out Why This Loop Is Malfunctioning -
so can't figure out what's wrong code. when process purchase, after enter amount of yogurt , told go enjoy it, after error message made if people don't input p or s, right afterwards goes normal when first enter program, tell me why is? thank you!
#include <iostream> #include <string> #include <sstream> using namespace std; int main() { string usercommand; int creditcount = 0; int userinput; while (creditcount >= 0) { cout << "--------menu--------\n" << "p (process purchase)\n" << "s (shutdown system)\n" << "--------menu--------\n" << "your choice: "; getline(cin, usercommand); if (usercommand[0] == 'p' || usercommand[0] == 'p') { if (creditcount >= 10) { cout << "you qualify free yogurt, use ten of credits (yes or no)?"; getline(cin, usercommand); if (usercommand[0] == 'y' || usercommand[0] == 'y') { creditcount = creditcount - 10; cout << "you used 10 credits , have " << creditcount << " left.\n" << "enjoy free yogurt!"; } else if (usercommand[0] == 'n' || usercommand[0] == 'n') { cout << "how many yogurts buy? "; cin >> userinput; if (userinput > 0) { creditcount = creditcount + userinput; cout << "you earned " << userinput << " stamps. have " << creditcount << " credits! enjoy yogurt!"; } else { cout << "invalid input, please try processing purchase again , enter positive " << "integer."; } } else { cout << "*error, please try processing purchase again , enter either yes or no*\n\n"; } } else if (creditcount < 10) { cout << "how many yogurts buy? "; cin >> userinput; if (userinput > 0) { creditcount = creditcount + userinput; cout << "you earned " << userinput << " stamps. have " << creditcount << " credits! enjoy yogurt!\n\n"; } else { cout << "invalid input, please try processing purchase again , enter positive " << "integer."; } } } else if (usercommand[0] == 's' || usercommand[0] == 's') { cout << "*shutting down system*\n"; return 0; } else { cout << "*error, please enter either p (for process purchase) or s (for shutdown system)*\n\n"; } } }
@acid1789 has pointed out correctly error due empty line after getline. code can make out using infinite loop here
while(creditcount >= 0){...} since creditcount never going less 0 instead of can use
while (true){...} its better programming practice.
and correct program can use
cin >> usercommand; instead of
getline(cin, usercommand); hope helps.
edit:- sorry python habits..
Comments
Post a Comment