gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-30 15:16:25 24 4
gpt4 key购买 nike

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

#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 发生了什么?它们在新输入时被删除吗?为什么?

提前致谢

最佳答案

Why is the size not the same?

用户输入是“hello\nhello\n”。

第一个 scanf("%99s%n", input, &inputSize) 扫描 "hello\n"。将 '\n' 视为尾随空白,将其放回 stdin 中。因此扫描 5 char,在 input 中保存 5 char。然后它将 '\0' 附加到 input

下一个 scanf("%99s%n", input, &inputSize) 扫描 "\nhello\n""%s" 扫描但不保存前导空格。将第二个 '\n' 视为尾随空白,将其放回 stdin 中。因此扫描 6 char,在 input 中保存 5 char。然后它将 '\0' 附加到 input

How can I get exact size every time?

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

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

正在发生。 input 是一个 char 数组 10。这肯定是程序的新运行,因此 10 的 ninput 中保存的 char 匹配,因为前面没有 '\n' 丢弃。

> AAAAAAAAAA
INPUT: AAAAAAAAAA, SIZE: 10

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

input 中保存的 A 会被 B 覆盖。

为什么最后的输出是“BBBBBAAAA”而不是“BBBBB”仍然是个谜。给定“SIZE:6”,怀疑 OP 转录错误。

关于c - 空白字符影响 scanf 输入的返回大小,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33103459/

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