如预期的程序控制流不工作 [英] The program control flow doesn't work as expected
问题描述
这是 C
的一个问题。未如预期的程序控制流。它问到输入字符但不能要求进入字符x。
INT富();INT主(INT ARGC,为const char * argv的[]){ 富();
返回0;
}INT富(){ 在烧焦;
焦X;
的printf(你想派对\\ n);
如果((在=的getchar())=='Y')
的printf(走睡眠!我是在开玩笑\\ n);
其他
的printf(哦,你是如此boaring .. \\ n);
的printf(\\ NOK,另一个问题\\ n);
的printf(想要去睡觉\\ n);
如果((X =的getchar())=='Y')
的printf(OK让去,困头\\ n);
其他
的printf(不,让我们去\\ n);
返回0;
}
要澄清上述意见,给予投入的过程中,你是pressing <大骨节病>是骨节病>然后pressing <大骨节病> ENTER 骨节病>。因此,是
被认为是输入第一个的getchar()
和 ENTER
键preSS [ \\ n
]存储在输入缓冲区。
在调用一个的getchar()
的 \\ n
读,这被认为是一个完全有效的为的getchar输入()
,因此您的code未等待下一个输入。
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;
}
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.
这篇关于如预期的程序控制流不工作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!