【问题标题】:how to understand scanf buffer and format in C? [duplicate]如何理解 C 中的 scanf 缓冲区和格式? [复制]
【发布时间】:2021-09-22 08:47:29
【问题描述】:

我依稀记得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 行中的 scanf("%c", &amp;option); 第二次运行时,输入第 24 行中最后一个 scanf("%s", buff); 中遗漏的 '\n' 字符,使 @ 987654324@ \n 和 switch 语句打印有关选项的投诉并跳到 while 循环。
我观察到如果我将scanf("%c", &amp;option); 更改为scanf(" %c", &amp;option);,问题就消失了。我应该如何理解这种现象?使用scanf函数时,%c或%s前有空格或制表符有什么作用?

【问题讨论】:

  • @RetiredNinja 是的,这回答了我的问题。谢谢!

标签: c char scanf whitespace


【解决方案1】:

来自 C 标准(7.21.6.2 fscanf 函数)

5 由空白字符组成的指令由 读取输入直到第一个非空白字符(保留 未读),或直到无法读取更多字符。

因此在调用 scanf 时使用带有前导空格的格式

scanf(" %c", &option);

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-01-21
    • 2015-05-23
    • 1970-01-01
    • 2013-01-09
    • 1970-01-01
    • 2021-07-11
    • 2010-12-09
    相关资源
    最近更新 更多