问题
This is a problem in C
. The program Control flow is not as expected. It ask to enter the character in but fail to ask to enter character x.
int foo();
int main(int argc, const char * argv[]) {
foo();
return 0;
}
int foo(){
char in;
char x;
printf("Do you wanna party \n");
if((in = getchar()) == 'y')
printf("Go Sleep!, I was kidding\n");
else
printf("Oh! you are so boaring..\n");
printf("\nOk, Another Question\n");
printf("Wanna Go to Sleep\n");
if((x = getchar()) == 'y')
printf("ok lets go, Sleepy Head\n");
else
printf("No, lets go\n");
return 0;
}
回答1:
To clarify the comments mentioned above, in the process of giving input, you're pressing Y and then pressing ENTER. So, the y
is considered as the input to first getchar()
, and the ENTER
key press [\n
] is stored in the input buffer.
On the call to next getchar()
, the \n
is read, which is considered a perfectly valid input for getchar()
and hence your code is not waiting for the next input.
来源:https://stackoverflow.com/questions/27513046/the-program-control-flow-doesnt-work-as-expected