Reputation: 333
I wrote this simple piece of code(it actually calculates sine, cosine or tangent values of x according to s,c or t given as input) which works fine until I tried to change the order of statements just a bit....this one works fine.....
#include<stdio.h>
#include<math.h>
void main()
{
char T;
float x;
printf("\nPress s or S for sin(x); c or C for cos(x); t or T for tan(x)\n\n");
scanf("%c", &T);
printf("Enter the value of x: ");
scanf("%f",&x);
if(T=='s'||T=='S')
{
printf("sin(x) = %f", sin(x));
}
else if(T=='c'||T=='C')
{
printf("cos(x) = %f", cos(x));
}
else if(T=='t'||T=='T')
{
printf("tan(x) = %f", tan(x));
}
}
*BUT*as soon as I change the arrangement to the following the compiler asks for the value of x and skips the scanf for char T and returns nothing... Can anybody explain what's happening here???
#include<stdio.h>
#include<math.h>
void main()
{
char T;
float x;
printf("Enter the value of x: ");
scanf("%f",&x);
printf("\nPress s or S for sin(x); c or C for cos(x); t or T for tan(x)\n\n");
scanf("%c", &T);
if(T=='s'||T=='S')
{
printf("sin(x) = %f", sin(x));
}
else if(T=='c'||T=='C')
{
printf("cos(x) = %f", cos(x));
}
else if(T=='t'||T=='T')
{
printf("tan(x) = %f", tan(x));
}
}
Upvotes: 1
Views: 429
Reputation: 726799
This is because scanf
for %c
takes a single character - any character, including '\n'
. When you hit "return" button after entering your float value, I/O system gives you the float, and buffers the "return" character. When you call scanf
with %c
, the character is already there, so it gives it to you right away.
To address this problem, create a buffer for a string, call scanf
with %s
, and use the first character of the string as your selector character, like this:
char buf[32];
printf("\nPress s or S for sin(x); c or C for cos(x); t or T for tan(x)\n\n");
scanf("%30s", buf);
T = buf[0];
Upvotes: 5