mardon mardon - 1 year ago 107
C Question

Bad input to double variable

I have iput two double variable in c and I need if one of the input is string terminate with print message i try something like this

double a, b;
printf("Input two variables:\n");
scanf("%lf %lf", &a, &b);
printf("%lf\n", a);
printf("%lf\n", b);
if(( a <= 0.0 ) || (b <= 0.0))
printf("Bad input\n");
return 2;

if I try input 4 fff (or fff 5) the program not print Bad input message.
Why this program not print Bad input message if set a=444 b=fff or a=ddd b=78?

Answer Source

You try and use a before validating the input is valid. This could lead to unexpected behavior. You need to validate your input, something like

if (scanf("%lf %lf", &a, &b) != 2) {
    // handle bad input
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download