Reputation: 160
i'm using code-blocks 16.01 when i debug this code it show me a correct output but when i run it it show incorrect output! how to solve this?
int main()
{
char ch[100],var[100],val[100],tempVa[100];
int i = 0,j=0,count=0;
while (1)
{
puts("Enter the expression (or (end) to exit):");
gets(ch);
if (strcmp(ch, "end") == 0 || strcmp(ch, "END") == 0)
exit(-1);
else if(2 == sscanf(ch,"%s = %s", var, val))
{ i = 0;
printf("Variable is : %s\t Value Before evaluating : %s\n",var, val);
while (i<=strlen(val))
{
while (val[i]!='-'&&val[i]!='%'&&val[i]!='/'&&val[i]!='*'&&val[i]!='+'&&i<strlen(val))
tempVa[j++]=val[i++];
i++;
for (count=0; count<strlen(tempVa); count++)
printf("%c", tempVa[count]);
for (count=strlen(tempVa); count>=0; count--)
tempVa[count]='\0';
j=0;
}
}
else
printf("Invalid!");
}
return 0;
}
Smaple Input : Hassan = Merna+Mohamed+Ahmed
From where does those garbage come?!
Upvotes: 1
Views: 377
Reputation: 2907
I tested your code and it works Edits:
Code:
#include <stdio.h>
#include <string.h> // edit
int main()
{
char ch[100], var[100], val[100], tempVa[100];
int i = 0, j = 0, count = 0;
while (1)
{
puts("\nEnter the expression (or (end) to exit):");
gets(ch);
if (strcmp(ch, "end") == 0 || strcmp(ch, "END") == 0)
return -1; // edit
else if(2 == sscanf(ch, "%s = %s", var, val))
{
i = 0;
printf("Variable is : %s\t Value Before evaluating : %s\n", var, val);
while (i <= strlen(val))
{
while (val[i] != '-' && val[i] != '%' && val[i] != '/' && val[i] != '*' && val[i] != '+' && i < strlen(val))
tempVa[j++] = val[i++];
i++;
for (count = 0; count < strlen(tempVa); count++)
printf("%c", tempVa[count]);
for (count = strlen(tempVa); count >= 0; count--)
tempVa[count] = '\0';
j = 0;
}
}
else
printf("Invalid!");
}
return 0;
}
Sample run:
Enter the expression (or (end) to exit): Hassan = Merna+Mohamed+Ahmed
Variable is : Hassan Value Before evaluating : Merna+Mohamed+Ahmed MernaMohamedAhmed
Enter the expression (or (end) to exit):
Upvotes: 1