user3313154
user3313154

Reputation: 3

The program prints unwanted things

Why the following program saves the + sign even loop should end when she sees this sign.

My code-

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

Target clearing the numbers after the multiplication sign up to + sign.

Thank helpers who could tell me why the software keeps + sign and suggest me way to fix it (:

Upvotes: 0

Views: 70

Answers (3)

Jonathan Leffler
Jonathan Leffler

Reputation: 753725

You access str1[-1] which invokes undefined behaviour.

You don't null terminate str1, so you print whatever values are in str1 after 46 too. You copy the + into the string, so that appears, but there could be other non-zero bytes in str1 after that. It would be better not to copy the + and to null terminate the string.

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

Upvotes: 3

Jimilian
Jimilian

Reputation: 3919

You code is incorrect. Because (j-1) may be negative and str1 is not initialized.

Upvotes: 1

Ian Kenney
Ian Kenney

Reputation: 6426

It keeps the plus sign because you break out of the while loop when the target string has a plus as the last character. You should test the source string instead - something like

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

Upvotes: 1

Related Questions