gpt4 book ai didi

c - 当我打印我的字符串时,它打印的长度超过了它的长度

转载 作者:行者123 更新时间:2023-12-01 21:45:34 27 4
gpt4 key购买 nike

我的代码

char str[100];
scanf("%s\n",str);
char str2[2];
scanf("%c\n",&str2[0]);
scanf("%c\n",&str2[1]);
printf("%s",str2);

输入

abbcde
b
c

输出

bcabbcde

如果 str2 的长度为 2 只是为什么所有这些额外的东西来自,我已经检查了两个字符串的输入是否正确记录。

最佳答案

工作代码如下

#include <stdio.h>

int main()
{
char str[100];
scanf("%s",str);
char str2[3];
scanf(" %c",&str2[0]);
scanf(" %c",&str2[1]);
str[2]='\0';
printf("%s",str2);

return 0;
}

修复 1:

Unrelated: trailing whitespace characters such as \n in scanf() -- @ex_nihilo already given a comment on this.

修复 2:

Space before %c removes any white space (blanks, tabs, or newlines)

修复 3:

If str2 is a string then the end character should be '\0' and we need to add this explicitly. For this we need to increase the size of str2 array to 3.

关于c - 当我打印我的字符串时,它打印的长度超过了它的长度,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60752183/

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