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?
scanf
s will return 1. Checking this is good,though... – Spikatrix44.67
, the firstscanf
consumes44
. The secondscanf
sees the.67
and consumes it as it is a valid decimal number . This is why the secondscanf
gets "skipped" – Spikatrixscanf
, eg:if (scanf("%d", &a) != 1) /* error */;
– pmg