1

依稀记得scanf有问题,今天又遇到了这个现象。我想这是一个众所周知的问题(?)。这是一个测试scanf的简单测试代码。

#include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>

int8_t buff[1024];

int main()
{
    char option;

    printf("Welcome to the demo of character device driver...\n");

    while (1) {
        printf("***** please enter your option *****\n");
        printf("           1. Write                 \n");
        printf("           2. Read                  \n");
        printf("           3. Exit                  \n");
        scanf("%c", &option);    // line 18
        printf("your option = %c\n", option);
        switch(option) {
            case '1' :
                printf("Enter the string(with no space) :\n");
                //scanf("%[\t\n]s", buff);
                scanf("%s", buff);    // line 24
                break;
            case '2' :
                printf("Data = %s\n", buff);
                break;
            case '3' :
                exit(1);
                break;
            default :
                printf("Enter valid option. option = %c\n", option);
        }
    }
}

当我运行它时(我使用调试器来跟踪它),当第 18 行第二次运行时,输入第 24 行scanf("%c", &option);最后一个省略的 '\n' 字符,然后 switch 语句打印有关选项的投诉并跳到 while 循环。 我观察到,如果我更改为,问题就消失了。我应该如何理解这种现象?使用 scanf 函数时,在 %c 或 %s 之前有空格或制表符有什么影响?scanf("%s", buff);option \n
scanf("%c", &option);scanf(" %c", &option);

4

1 回答 1

0

来自 C 标准(7.21.6.2 fscanf 函数)

5 由空白字符组成的指令通过读取输入直到第一个非空白字符(仍然未读取)或直到无法读取更多字符来执行。

因此使用带有前导空格的格式,就像在这个 scanf 调用中一样

scanf(" %c", &option);

导致跳过输入流缓冲区中的空白。

于 2021-07-13T09:56:38.840 回答