[英]Why does scanf fail but fgets works?
我要求用户输入是否要退出该程序。 有两个摘要。 一个使用scanf()函数读取输入,而第二个使用fgets()函数读取输入。 使用scanf(),程序进入无限循环。 使用fgets(),程序将按预期执行。 为什么scanf()失败,而fgets()有效? 我该如何纠正它,以便scanf()起作用? 这是代码:
首先是用scanf()
#include <stdio.h>
#include <string.h>
int main(void)
{
char yesNo[6];
printf("Enter [quit] to exit the program, or any key to continue");
scanf("%s", &yesNo[6]);
while (strcmp(yesNo,"quit\n") != 0)
{
printf("Enter [quit] to exit the program, or any to continue");
scanf("%s", &yesNo[6]);
}
return 0;
}
第二个是fgets()
#include <stdio.h>
#include <string.h>
int main(void)
{
char yesNo[6];
printf("Enter[quit] to exit the program, or any key to continue: ");
fgets(yesNo, 6, stdin);
while (strcmp(yesNo,"quit\n") != 0)
{
printf("Enter [quit] to exit the program, or any key to continue:");
fgets(yesNo, 6, stdin);
}
return 0;
}
您必须记住的scanf("%s")
和fgets
之间的区别是它们接受输入的方式。
%s
指示scanf
放弃所有前导空白字符,并读入所有非空白字符,直到出现空白字符(或EOF
)为止。 它将所有非空格字符存储在其对应的参数中(在本例中为yesNo
,然后将最后一个空格字符留回到标准输入流( stdin
)中。 它还以NUL终止其相应的参数,在这种情况下为yesNo
。
fgets
读取所有输入,直到换行符( '\\n'
)或读取的最大字符数作为第二个参数减一个(对于NUL终止符'\\0'
)被读取为止(或直到EOF
),所有这些输入(包括\\n
)都存储在其第一个参数yesNo
,并且以NUL终止。
因此,如果您有scanf("%s", yesNo);
输入quit\\n
, yesNo
将仅包含quit
并将\\n
保留在stdin
。 由于字符串"quit"
和"quit\\n"
不同,因此strcmp
不会返回零, while
循环将继续循环。
对于fgets(yesNo, 6, stdin);
输入quit\\n
, yesNo
将保留quit\\n
,并且stdin
将为空。 当字符串"quit\\n"
和"quit\\n"
相等时, strcmp
返回零,并且执行退出循环。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.