所以我有以下代码:
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);
}
Run Code Online (Sandbox Code Playgroud)
当我使用输入时P
,我的输出do_something()
完成后是:
"output from do_something() function"
command= P
Non-valid input
Run Code Online (Sandbox Code Playgroud)
我的问题是为什么我仍然在第一个if语句中调用Non-valid input
after do_something()
?AKA为什么在do_something()
完成时仍然会运行?
你else
在第二个之前省略了if
,这意味着如果command != 'Q'
(这是真的P
),exit
将执行该块.
你可能想做
if ( command == 'P' ) {
do_something();
}
else if ( command == 'Q' ) { // Note the 'else'
cout << "Exit\n";
exit(0);
}
else {
cout << "command= " command << endl; //use for debugging
cout << "Non-valid input\n";
exit(1);
}
Run Code Online (Sandbox Code Playgroud)
这样,当该命令P
,do_something
将被称为和所有其余的将被跳过.