[英]Strange output using if/else in C++
So I have the following code: 所以我有以下代码:
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);
}
When I use input of P
, my output after do_something()
finishes is: 当我使用
P
输入时, do_something()
完成后的输出是:
"output from do_something() function"
command= P
Non-valid input
My question is why do I still get the Non-valid input
after do_something()
is called in the first if statement? 我的问题是,为什么在第一个if语句中调用
do_something()
之后仍然获得Non-valid input
? AKA why does the else still run when do_something()
finishes? AKA为什么
do_something()
完成时else仍然运行?
You left out the else
before the second if
, which means that if command != 'Q'
(which is true for P
), the exit
block will be executed. 您在第二个
if
之前保留了else
,这意味着如果command != 'Q'
(对于P
是正确的),则将执行exit
块。
You probably meant to do 你可能想做
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);
}
That way, when the command is P
, do_something
will be called and all the rest will be skipped. 这样,当命令为
P
,将调用do_something
,其余的将被跳过。
Your else
is associated with second if
not the first one. 您的
else
与第二个( if
不是第一个)关联。 So after finishing first if
it enters the else
part of second if. 因此,在完成第一个
if
之后进入第二个if的else
部分。 Thats why you are getting this. 那就是为什么你得到这个。 You should use this
你应该用这个
char command;
cin >> command;
if ( command == 'P' ) {
do_something();
}
else 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);
}
The two if
statements are independent of each other... The else is with the second if
condition. 两个
if
语句彼此独立... else是第二个if
条件。 So it never goes into the second if
condition and always into its else
part. 所以,它永远不会进入第二个
if
条件永远为它的else
部分。 The first if
condition has no else
part. 第一个
if
条件没有else
部分。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.