So I have the following code:
char command;
cin >> command;
if ( command == 'P' ) {
do_something();
}
if ( command == 'Q' ) {
cout << "Exit\n";
exit(0);
}
else {
cout << "command= " command << endl; //use for debugging
cout << "Non-valid input\n";
exit(1);
}
cout << "exit at completion\n";
exit(0);
}
When I use input of P, my output after do_something() finishes is:
"output from do_something() function"
command= P
Non-valid input
My question is why do I still get the Non-valid input after do_something() is called in the first if statement? AKA why does the else still run when do_something() finishes?
You left out the
elsebefore the secondif, which means that ifcommand != 'Q'(which is true forP), theexitblock will be executed.You probably meant to do
That way, when the command is
P,do_somethingwill be called and all the rest will be skipped.