在C++中使用if/else的奇怪输出

Tay*_*ton 2 c++ if-statement

所以我有以下代码:

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 inputafter do_something()?AKA为什么在do_something()完成时仍然会运行?

Set*_*gie 5

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将被称为和所有其余的将被跳过.

  • @LuchianGrigore&Seth Carnegie你们如何设法快速回答这个问题.只是坐着潜伏着什么?; o)...... (3认同)