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?
scanfs will return 1. Checking this is good,though...44.67, the firstscanfconsumes44. The secondscanfsees the.67and consumes it as it is a valid decimal number . This is why the secondscanfgets "skipped"scanf, eg:if (scanf("%d", &a) != 1) /* error */;