繁体   English   中英

为什么scanf失败但fgets有效?

[英]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\\nyesNo将仅包含quit并将\\n保留在stdin 由于字符串"quit""quit\\n"不同,因此strcmp不会返回零, while循环将继续循环。

对于fgets(yesNo, 6, stdin); 输入quit\\nyesNo将保留quit\\n ,并且stdin将为空。 当字符串"quit\\n""quit\\n"相等时, strcmp返回零,并且执行退出循环。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM