奇怪的输出,使用if/else c 中的if/else
Strange output using if/else in C++
所以我有以下代码:
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
部分。
相关文章:
- 我的简单if-else语句是如何无法访问的代码
- 如何删除peer if else分支中的冗长句子
- 我似乎对if/else的基本语句有问题:/
- 使用if-else将数字转换为单词
- 为什么这个案例陈述需要一个"if else"而不仅仅是一个"if"?
- C++ If/Else 语句被跳过
- 如果条件不相关,我应该更喜欢两个 if 语句而不是 if-else 语句吗?
- 如何将 if else 语句重写为 switch 语句
- 在 C++ 中的 if-else if- else 语句期间更改变量
- 为什么我的 if else 语句不起作用并从数组中输出正确的索引?
- 我的 If Else 语句无法在向量 (C++) 中提供最大值
- 具有嵌套 if-else 的循环的时间复杂度
- 为什么无论输入如何,所有 if-else 语句都会打印?
- 简化对两个布尔值的 4 个 if/else 检查
- 如何在C++中创建 if else 循环而不是多个嵌套?
- 为什么切换 if else 语句的顺序会导致错误?
- 如何使用 if else 语句
- if/else 语句输出由于加号或减号而未显示正确的消息
- 如何解释 #if/#else 位域?(VC++菜鸟)
- if-else 语句仅按特定顺序工作,我不知道为什么