gpt4 book ai didi

c - 使用 strcat 时添加的随机空格

转载 作者:太空宇宙 更新时间:2023-11-04 08:02:37 25 4
gpt4 key购买 nike

我正在尝试不断地将 char 添加到字符串的末尾。我通过在我的 main 中运行它来做到这一点

 char String[256];
char alphabets[26] = "abcdefghijklmnopqrstuvxyz";
for (int i = 0; i < 257; i++) {

char newChar = alphabets[indexOfNewChar-1];
printf("new char = %c\n",newChar);
strcat(String,&newChar);

printf("%s\n",String);
}

当我运行这堆代码时,它被打印出来
新字符 = b
bk ho btj
dfhhai bbdhgfcafgcfi bbaccfeai afebaci aedgdddai hei hfedhbi dabeedbi i cfhi i caddbhgbi i acfi cehbhcddcahbhbabi aaadi 嗨 ffhhccbccfbbfggfdhebgeacecai cefdcdb

如您所见,运行期间随机出现空格和新行。在意识到这些随机空间的出现后,我尝试用

char* removeSpaces(char* input)
{
int i,j;
char *output=input;
for (i = 0, j = 0; i<strlen(input); i++,j++)
{
if (input[i]!=' ')
output[j]=input[i];
else
j--;
}
output[j]=0;
return output;
}

但是,这并没有真正影响结果,因为仍然出现空白。我怎样才能删除那些空格或更好地阻止它们出现。在旁注中,代码在 for 循环重复 160 多次后终止。我怎样才能克服这个问题。

最佳答案

newChar 是单个 char&newChar 不是字符串。不是。字符串需要空终止符; strcat 正在寻找一个,并连接它找到的杂散字符,直到找到一个(尽管这是未定义的行为,因此它可能导致程序崩溃)。

关于c - 使用 strcat 时添加的随机空格,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45064359/

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