c - 在 C 中没有附加参数的 scanf

标签 c scanf

是否允许在没有附加参数的情况下使用 scanf("") 来忽略初始空格?
我正在使用 getchar() 读取单词的字符,我想忽略单词前的空格(后面的空格用于检查单词的结尾)。
代码如下,对吗?

char *read_word() {
    int size = 2;
    int char_count = 0;
    char *s;
    char ch;

    s = mem_alloc(size);

    scanf(" ");

    while ((ch = getchar()) != EOF) {
        if (char_count >= size) {
            s = mem_realloc(s, size++);
        }

        if (ch == ' ' || ch == '\n') {
            s[char_count] = '\0';
            break;
        }

        s[char_count++] = ch;
    }

    return s;
}

最佳答案

根据 scanf() 函数的定义 (*),强调我的:

The format is composed of zero or more directives: one or more white-space characters, an ordinary multibyte character (neither % nor a white-space character), or a conversion specification.

[...]

A directive composed of white-space character(s) is executed by reading input up to the first non-white-space character (which remains unread), or until no more characters can be read.

所以 scanf( ""); 是完全有效的。


(*):ISO/IEC 9899:1999,7.19.6.2 fscanf 函数,第 3 节和第 5 节。

其他*scanf 函数在本节中定义。

关于c - 在 C 中没有附加参数的 scanf,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35346522/

相关文章:

c++ - 如何通过 cstdio::scanf 在一行中读入三个整数?

objective-c - 创建编程语言问题

c - fprintf 到 .txt 文件中给我 ‰‰‰‰‱‱‱‱‱‱ 而不是 0 0 0 0 1 1 1 1 1 1 1

c - 是什么让您成为 C 编程专家?

c - short int Integer wrap around/short int inversion in c 不理解,分配和打印之间的区别

c - 当格式字符串以换行符结尾时,scanf 的行为是什么?

c++ - C++ 中的 Sscanf(读入值并同时赋值)

c - "undefined reference to ' cblas_ddot '"使用cblas库时

c++ - std::apply-ing sscanf 到元组中,元组未完全更新

c - 如何解决电子邮件的 sscanf 问题?