Reputation: 83
I have the following code in C:
#include <stdio.h>
#include <stdlib.h>
int var();
int var()
{
return 10;
}
void main()
{
int a;
double x;
a=0;
a=var();
printf("hello world, i am a function which returned the value %d",a);
printf("\nnow you enter a value:");
scanf("%d",&a);
printf("so you entered the value: %d",a);
printf("\nnow enter a double value:");
scanf("%lf",&x);
printf("The double number till 4 precision is: %0.4lf",x);
}
When I input normal integer and double values for the two scanf it runs fine. However I want to make it more robust. If I enter a decimal value for int scanf the code jumps directly to the next printf and skips the scanf for double. It prints the decimal part that I have input in the int as the double value.
eg:
hello world, i am a function which returned the value 10
now you enter a value:44.67
so you entered the value: 44
now enter a double value:The double number till 4 precision is: 0.6700
Any help?
Upvotes: 0
Views: 1018
Reputation:
You should use the function fpurge()
to erase any input or output buffered in the given stream (which is stdin
in this case).
Try this:
#include <stdio.h>
#include <stdlib.h>
int var();
int main(int argc, char *argv[]) {
int a;
double x;
a = 0;
a = var();
printf("Hello world, I am a function which returned the value %d.\n", a);
printf("Now you enter a value: ");
scanf("%d", &a);
printf("So, you entered the value %d.\n", a);
printf("Now enter a double value: ");
fpurge(stdin);
scanf("%lf", &x);
printf("The double number till 4 precision is %.4lf.\n", x);
return 0;
} // End main
int var() {
return 10;
}
Here is the output which I got:
Hello world, I am a function which returned the value 10.
Now you enter a value: 44.67
So, you entered the value 44.
Now enter a double value: 3.14159
The double number till 4 precision is 3.1416.
Upvotes: 1
Reputation: 409442
It's tricky because a number with fractions (like e.g 12.34
) do have a valid integer part, which is read and correctly parsed by the first scanf
call.
The simplest solution is to use e.g. fgets
to read the input into a buffer, and then use sscanf
on that buffer.
Upvotes: 1