空白字符影响从 scanf 返回的输入大小

Whitespace characters affects returned size of input from scanf

我正在使用此代码来捕获用户的标准输入,然后打印回保存的字符数。

#include <stdio.h>

int main()
{
    char input[100];
    int inputSize;
    while (scanf("%99s%n", input, &inputSize) != EOF)
    {
        printf("INPUT: %s, SIZE %d\n", input, inputSize);
    }
    return 0;
}

结果如下:

> hello
INPUT: hello, SIZE: 5
> hello
INPUT: hello, SIZE: 6

为什么大小不一样? 我怎样才能每次都得到准确的尺寸?

最后: char变量是数组,对吧? 那为什么这不会发生呢?

> AAAAAAAAAA
INPUT: AAAAAAAAAA, SIZE: 10
> BBBBB
INPUT: BBBBBAAAAA, SIZE: 6

保存 10x A 发生了什么?它们在新输入时被删除?为什么?

提前致谢

scanf("%99s%n", input, &inputSize)

将在 "input" 的前 x 个字节上写入读取的 x 个字符。 你可以试试

scanf("%99s%n", &input[TotalAmountOfBytesRead], &inputSize)

然后,它会将第一个未写入的字节的地址提供给scanf。 不过要小心缓冲区溢出(提示:malloc()/realloc())。

Why is the size not the same?

用户输入是"hello\nhello\n"。

第一个 scanf("%99s%n", input, &inputSize) 扫描 "hello\n"。将 '\n' 视为尾随白色-space,将其放回 stdin。所以扫描了5char,在input中节省了5char。然后它将 '[=18=]' 附加到 input.

下一个 scanf("%99s%n", input, &inputSize) 扫描 "\nhello\n""%s" 扫描但不保存前导白色-space。将第二个 '\n' 视为尾随白色-space,将其放回 stdin。所以扫描了6char,在input中节省了5char。然后它将 '[=18=]' 附加到 input.

How can I get exact size every time?

输入相同的内容 - 在第一个 "Hello" 之前输入 Enter"%s" 在行尾 之前 结束扫描。真正的解决方案是不使用 scanf()。如果用户输入是 line 导向的,使用 fgets()getline() 然后根据需要解析。

... The char variable is array, right? Then why this does NOT happen?

正在发生。 inputchar 的数组 10。这当然是程序的新 运行,因此 n of 10 匹配 char 保存在 input 中,因为没有前面的 '\n' 可以丢弃。

> AAAAAAAAAA
INPUT: AAAAAAAAAA, SIZE: 10

What happened to saved 10x A? They are deleted on new input? Why?

input 中保存的 AB 覆盖。

为什么最后的输出是 "BBBBBAAAAA" 而不是 "BBBBB" 仍然是个谜。鉴于 "SIZE: 6",怀疑 OP 转录错误。