I made a small C calculator earlier today, and I noticed it worked fine when the only operation it was able to do was addition, however when I tried to add subtraction, multiplication or division, it would simply not give an output, and I don’t know the reason for it as another calculator I had made before (although much simpler) was able to do a similar process fine.
I am very new to C and programming in general though (C is the first programming language I am just picking up) so it might just be my fault.
This is the code on my program for now:
int main()
{
int x;
int y;
int z;
char c;
printf("Number calculator advanced\n");
printf("please enter 2 digits\n");
scanf("%d%c%d",&x,&c,&y);
if (c == '+')
{
z = x += y;
printf("%d\n",z);
}
if (c == '-')
{
z = x -= y;
printf("%d\n",z);
}
}
as you know, I was expecting it to scan for the user’s math equation, and when a ‘-‘ or a ‘+’ was used, it would subtract or add both numbers, as it does for addition when it’s the only "if" statement that is used
The result I end up getting though, is this:
Number calculator advanced
please insert 2 digits
example: 5 + 2
Process returned 0 (0x0) execution time: 19.943 s
press ENTER to continue
>Solution :
The problem is how you’re using scanf. It isn’t taking into account there might be spaces.
"%d%c%d" matches an integer, a character, and an integer with no spaces between the first integer and the character.
"%d %c %d" matches an integer, 0 or more spaces, a character, 0 or more spaces, and an integer.
From the scanf docs…
whitespace characters: any single whitespace character in the format string consumes all available consecutive whitespace characters from the input (determined as if by calling isspace in a loop). Note that there is no difference between "\n", " ", "\t\t", or other whitespace in the format string.