调用scanf()的又一个字符串输入函数创建幻影输入 [英] Calling scanf() after another string input function creates phantom input
问题描述
下面是一个小程序:
#include <stdio.h>
int main() {
char str[21], choice[21]; int size;
while(1){
printf("$ ");
fgets(str, 20, stdin);
printf("Entered string: %s", str);
if(str[0] == 'q') {
printf("You sure? (y/n) ");
scanf("%s", choice);
if(choice[0] == 'y' || choice[0] == 'Y')
break;
}
}
return 0;
}
它读取使用与fgets一个字符串()
。如果字符串开头的①
时,如果用户想退出,并退出印证如果用户键入是
。
It reads a string using fgets()
. If the string starts with a q
, it confirms if the user wants to quit, and exits if the user types y
.
当我运行它,然后键入①
,出现这种情况:
When I run it and type q
, this happens:
$ q
Entered string: q
You sure? (y/n) n
$ Entered string:
$
请注意在 $输入的字符串:
。显然,与fgets()
有一个空字符或什么作为输入,即使我没有输入任何东西。
Note the $ Entered string:
. Clearly, fgets()
got an empty character or something as input, even though I didn't type anything.
这是怎么回事?
推荐答案
正如在其他的答案中描述 scanf函数
呼叫离开输入缓冲区换行,你也可以使用的getchar()
这样的scanf函数后:
As described in other answer scanf
call leaves the newline in the input buffer you can also use getchar()
after scanf like this :
scanf("%20s", choice);// always remember( & good) to include field width
// in scanf while reading
字符串否则将在很大程度上字符串`
Strings otherwise it will overwrite buffer in case of large strings `
getchar(); //this will eat up the newline
此外,您还应该使用与fgets这样的:
Besides , you should also use fgets like this :
fgets(str,sizeof str, stdin); //Its better
这篇关于调用scanf()的又一个字符串输入函数创建幻影输入的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!