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