0
Follow
0
View

C language input abcd but output accd

edwardtimzqy 注册会员
2023-02-27 18:41

该回答引用GPTᴼᴾᴱᴺᴬᴵ
问题出在定义字符数组 c 上。在 C 语言中,字符数组的定义方式如下:

char c[] = {'a', 'b', 'c', '\0'};


这里用花括号括起来的是一个字符数组的初始化列表,其中每个元素都是一个字符。

在你的代码中,定义字符数组时使用了单引号,这样只会初始化一个字符而不是字符数组。因此,当你输入 "abcd" 时,实际上只有 "a" 被存储到了字符数组 c 中,而后续的字符 "b"、"c" 和 "d" 都没有被存储。

由于 len 的值仍然为 1,因此 for 循环只会执行一次,只有字符 "a" 被处理。这就是为什么你观察到的输出是 "accd",因为字符数组 c 中只有一个字符 "a" 被处理了,后续的字符 "b"、"c" 和 "d" 都没有被处理。

要解决这个问题,你可以使用以下方式定义字符数组 c,并且要确保数组大小足够存储输入的字符串:

char c[100];


另外,gets 函数在最新的 C11 标准中已被标记为废弃,因为它无法保证输入数据不会超出数组边界。你可以考虑使用 fgets 函数代替 gets,并且需要指定读取数据的最小长度。例如:

char c[100];
fgets(c, sizeof(c), stdin);



这样就能够恰当读取并处理输入的字符串了。

liuhongyan7923 注册会员
2023-02-27 18:41

but my len actually prints 4 instead of 1, so why is only a processed and b converted to c

dajinnan 注册会员
2023-02-27 18:41
< div class = "md_content_show e397 data - v - 3967" = "" >

c array definition, add a length.

char c[10] = {'\0'};

cutecoconut 注册会员
2023-02-27 18:41
< div class = "md_content_show e397 data - v - 3967" = "" >

think excuse me this is what idea is there

lovedjj07590 注册会员
2023-02-27 18:41
< div class = "md_content_show e397 data - v - 3967" = "" >

?? Why is that? It's dev. Doesn't the compiler work?

czmike 注册会员
2023-02-27 18:41

I am normal

img