gpt4 book ai didi

c - 该程序打印不需要的东西

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

为什么下面的程序保存+号偶数循环应该在她看到这个标志时结束。

我的代码-

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

int main()
{
char str[10]= "2+48*46+1";
char str1[10];
int i,j = 0;

for(i = 0; i<10; i++)
{
if(str[i] == '*')
{
while(str1[j-1] != '+' )
{
str1[j] = str[i+1];
i++;
j++;
}
}
}
printf("%s\n",str1);
}

目标是清除乘号到+号后的数字。

感谢能告诉我为什么软件保留 + 号并建议我修复它的方法的帮助者 (:

最佳答案

您访问调用未定义行为的 str1[-1]

您不会 null 终止 str1,因此您也在 46 之后打印 str1 中的任何值。您将 + 复制到字符串中,这样它就会出现,但在那之后 str1 中可能还有其他非零字节。最好不要复制 + 并以 null 终止字符串。

j = 0;
while (str[i+j] != '+')
str1[j++] = str[i+j];
str1[j++] = '\0';
printf("%s\n", str1);

关于c - 该程序打印不需要的东西,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21813015/

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