奇怪的输出,使用if/else c 中的if/else

Strange output using if/else in C++

本文关键字:if else 中的 使用 输出      更新时间:2023-10-16

所以我有以下代码:

char command;
cin >> command;
if ( command == 'P' ) {
    do_something();
}
if ( command == 'Q' ) {
    cout << "Exitn";
    exit(0);
}
else {
    cout << "command= " command << endl; //use for debugging
    cout << "Non-valid inputn";
    exit(1);
}
cout << "exit at completionn";
exit(0);
}

当我使用P的输入时,do_something()完成后的输出是:

"output from do_something() function"
command= P
Non-valid input

我的问题是,为什么在第一个if语句中调用do_something()之后我仍然要获得Non-valid input?aka,为什么do_something()完成时仍会运行其他?

您在第二个if之前遗漏了else,这意味着如果command != 'Q'P是正确的),将执行exit块。

您可能打算做

if ( command == 'P' ) {
    do_something();
}
else if ( command == 'Q' ) { // Note the 'else'
    cout << "Exitn";
    exit(0);
}
else {
    cout << "command= " command << endl; //use for debugging
    cout << "Non-valid inputn";
    exit(1);
}

这样,当命令为 P时,将调用do_something并跳过所有其余的。

您的else第二 if不是第一个。因此,完成第一个if后,它将进入第二个IF的else部分。那就是为什么你得到这个。您应该使用此

char command;
cin >> command;
if ( command == 'P' ) {
    do_something();
}
else if ( command == 'Q' ) {
    cout << "Exitn";
    exit(0);
}
else {
    cout << "command= " command << endl; //use for debugging
    cout << "Non-valid inputn";
    exit(1);
}
cout << "exit at completionn";
exit(0);
}

两个 if语句彼此独立...其他情况是第二个if条件。因此,它永远不会进入第二个if条件,并且始终进入其else部分。第一个if条件没有else部分。