Reputation: 19
I'm new at c programming and I tried to write this basic program below but it keeps skipping the second scanf function(scanf(" %c", &sign)) whatever I do. Do you have any idea to solve this problem? In addition, I tried to use getchar function but it didn't work too.
#include <stdio.h>
int main()
{
int num1, num2, mult, sum, subt;
char sign;
printf("Enter two numbers: ");
scanf("%d%d", &num1, &num2);
printf("\nEnter operator type: ");
scanf(" %c", &sign);
if(sign == '*')
{mult = num1 * num2;
printf("\nResult is %d\n\n\a", &mult);}
else if(sign == '+')
{sum = num1 + num2;
printf("\nResult is %d\n\n\a", &sum);}
else if(sign == '-')
{subt = num1 - num2;
printf("\nResult is %d\n\n\a", &subt);}
else
printf("\nOperator is not valid, program has ended\n\n\a");
system("pause");
return 0;
}
Upvotes: 1
Views: 142
Reputation: 354
The problem is in these lines
printf("\nResult is %d\n\n\a", &mult);
printf("\nResult is %d\n\n\a", &sum);
printf("\nResult is %d\n\n\a", &subt);
Take off the ampersand &
. You don't want to print the memory addresses of the variables (which are the large, seemingly random numbers), you want the values stored in the variables.
Upvotes: 3
Reputation: 153368
The problem is not enabling all warnings.
A good well enabled compiler will warn about:
int subt;
printf("\nResult is %d\n\n\a", &subt);}
with something like
warning: format '%d' expects argument of type 'int', but argument 2 has type 'int *' [-Wformat=]
To not just solve the little problem, but get to higher level issues, the best things to learn here is to use available resources to help you write error-free code efficiently.
With gcc, consider:
gcc -pedantic -Wall -Wextra -Wconversion ..."
Upvotes: 0