该程序打印不需要的东西

时间:2014-02-16 15:13:06

标签: c string

为什么以下程序保存+符号偶数循环应该在她看到此符号时结束。

我的代码 -

#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);
}

目标在乘号后清除数字符号+符号。

感谢帮助者,他们可以告诉我为什么软件会保留+符号并建议我修复它的方法(:

3 个答案:

答案 0 :(得分:3)

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

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

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

答案 1 :(得分:1)

它保持加号,因为当目标字符串有一个加号作为最后一个字符时,你会跳出while循环。你应该测试源字符串 - 比如

while(str[i+1] != '+' )
    {
        str1[j++] = str[++i];
    }

答案 2 :(得分:1)

您的代码不正确。因为(j-1)可能是负数而str1未初始化。

相关问题