1

This is the code I am executing:

scanf("%s",expr);
i=0,j=0;
while(expr[i]!='+')
{
    l[j++]=expr[i++];
}
    j=0;

while(expr[i]!='=')
{
    r[j++]=expr[i++];
}
    j=0;

while(expr[i]!='\0')
{
    s[j++]=expr[i++];
}
printf("%s %d %s %d %s %d",l,strlen(l),r,strlen(r),s,strlen(s));

I cannot understand why this is not showing proper output. For e.g. in case of 1+1=2 Output should have been 1 1 +1 2 =2 2 But what i am getting is 1 2symbols 3 +1 2 =2 3symbols 5

2
  • 2
    You need to properly terminate all strings in C. Commented Apr 1, 2014 at 17:44
  • Yeah Got it. Thanks, sometimes small things mess up entire code; Commented Apr 1, 2014 at 17:48

1 Answer 1

1

Add \0 at the end of each string.

scanf("%s",expr);
i=0,j=0;

while(expr[i]!='+')
{
    l[j++]=expr[i++];
}
l[j]='\0'; //here
j=0;

while(expr[i]!='=')
{
    r[j++]=expr[i++];
}
r[j]='\0'; //here
j=0;

while(expr[i]!='\0')
{
    s[j++]=expr[i++];
}
s[j]='\0'; //and here

printf("%s %d %s %d %s %d",l,strlen(l),r,strlen(r),s,strlen(s));
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.