-
f1 =P
*hmm..I can't seem to make this code to work,it always bypasses reading the "operation" and doesn't read it.I would apperciate it ,if you could help me out..thnx in advance =)
**program basically reads 2 float numbers from the user and a character '*', '-' , '/', '+' and does one of these operations and prints out the result..and also goes into a loop~
***operations is a subprogram..I think that covers it all..I know 1st post shouldn't be a question..sorry & thnx ..
Sample example ( user input in bold )
Enter first number 3.4
Enter second number 2.7
Enter operation +
The result of 3.4 + 2.7 = 6.1
Another operation ? ( Y/N ) Y
Enter first number 1.2
Enter second number 4.0
Enter operation /
The result of 1.2 / 4.0 = 0.3
Another operation ? ( Y/N) N
Code:
#include <stdio.h>
#include <conio.h>
void math (float a, float b,char f)
{
float result;
if ( f=='+')
result = a+b;
else if (f=='-')
result = a-b;
else if (f=='*')
result = a*b;
else if (f=='/')
result = a/b;
esle
print("wrong input");
printf("result = %f",result);
}
void main()
{
float x,y;
char operation,answer;
do{
printf("enter 1st number\n");
scanf("%f",&x);
printf("enter 2nd number\n");
scanf("%f",&y);
printf("enter operation \n");
scanf("%c",&operation);
math(x,y,operation);
printf("Do it again?\n");
scanf("%c",&answer);
}while((answer=='y')||(answer=='Y'));
getch();
}
-
Add a space before "%c" to make it " %c", and it will skip the newline left behind by the previous scanf() operation.
--
Mats
-
....
lol..tht was the issue -.-...kinda annoying..well, thank you, but I wanna learn..so could u exlain a lil more in details..about why to leave space..i would be greatly thankful
thanks anyways =)
-
scanf (and it's relatives) will read as much data as it can according to the format. So %f will read a floating point number, including sign, numbers, one decimal point and exponent. Once it can not read any more "number stuff" it leaves whatever is left in the input buffer. In the normal case, that maens that you have a newline left behind after the number has been read (because you hit enter to "enter" the number, and enter "is" newline ('\n')).
When you add a space to the format string, the space means "read any number of whitespaces" - and newline counts as whitespace.
For most types of input, whitespace is automatically "eaten" by the magical scanf whitespace muncher, but not for %c or %s.
--
Mats
-
ok ,that helped alot ..now I understand a lil more about C.
Thanks,mr.Mats =)