gpt4 book ai didi

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

转载 作者:太空狗 更新时间:2023-10-29 16:35:06 26 4
gpt4 key购买 nike

是否允许在没有附加参数的情况下使用 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/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com