gpt4 book ai didi

c - 在线扫描单个字 (C)

转载 作者:行者123 更新时间:2023-11-30 17:43:04 27 4
gpt4 key购买 nike

我的目标是制作一个程序,可以扫描输入中的单词,然后将其保存到一个大字符串中。

我确信输入始终是单词 '\n' 单词 '\n' ...

因此,我尝试扫描单个字符并将其保存到数组中,并将 '\n' 替换为 ' '

我的代码:

char c;
char *line;
int len = 0;

while(!feof(stdin))
{
len++;
char *line = (char *)malloc(sizeof(char) * len);
scanf("%c", &c);
if (c == '\n')
line[len - 1] = ' ';
else
line[len - 1] = c;
}

int q;
for(q = 0; q < len - 1; q++)
printf("%c", line[q]);

输出错误。 (RUN FAILED(退出值1,总时间:2s)

例如我想要输入:

one
two
three
four
five

这用于输出:

"one two three four five"

最佳答案

每次 while 循环时,您都会分配一个新的,并丢弃旧值及其中的字符。除了最后一个字符之外,您不会初始化任何内容,因此当循环结束时,除了最后一个字符之外,line 都是垃圾。您只想在开始时分配一个足够大的缓冲区一次,或者使用 realloc 使缓冲区更大。

你有 while(feof(stdin)) 这几乎总是错误的 - feof 仅在无法从输入中读取字符后才为真。所以你最终会循环太多次,重复最后一个字符。检查 scanf 的返回值。

关于c - 在线扫描单个字 (C),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20317064/

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