gpt4 book ai didi

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

转载 作者:搜寻专家 更新时间:2023-10-31 00:17:35 25 4
gpt4 key购买 nike

所以我有以下代码:

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);
}

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

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

我的问题是为什么在第一个 if 语句中调用 do_something() 之后我仍然得到 Non-valid input?也就是为什么当 do_something() 完成时 else 仍然运行?

最佳答案

您在第二个 if 之前省略了 else,这意味着 if command != 'Q'(对于 P), exit block 将被执行。

你可能是想做的

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);
}

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

关于c++ - 在 C++ 中使用 if/else 的奇怪输出,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13036864/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com