首页 文章

为什么scanf失败但fgets有效?

提问于
浏览
-1

我要求用户输入是否要退出程序 . 有两个片段 . 一个使用scanf()函数读取输入,而第二个使用fgets()函数读取输入 . 使用scanf(),程序进入无限循环 . 使用fgets(),程序按预期执行 . 为什么scanf()失败,fgets()工作?我如何纠正它,以便scanf()可以工作?这是代码:

First is with 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;
}

Second is with 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;
}

1 回答

  • 2

    您需要记住的是 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\nyesNo 将保持 quit\nstdin 将为空 . strcmp 返回零,因为字符串 "quit\n""quit\n" 都相等,并且执行从循环中出来 .

相关问题