Home > Blockchain >  scanf double returns garbage value if entered characters
scanf double returns garbage value if entered characters

Time:07-27

scanf("%lf", &Deposit_Amount); 

This statement returns garbage value instead of 0.00 when I enter a character.

Here's my code


   double Deposit_Amount;

   StartDepositInput:;
   system("cls");
   printf("Enter amount to deposit: ");
   scanf("%lf", &Deposit_Amount); // when I enter 'g'
   fflush(stdin); 
   printf("%lf", Deposit_Amount); // it outputs 1802842372383946000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000.00 

Isn't the scanf should return 0.0 if I input not a valid double?

CodePudding user response:

you need to check scanf return value

if(scanf("%lf", &Deposit_Amount) != 1) 
{
    Deposit_amount = 0.0;
    /* some other error handling */
}

You should not flush stdin

CodePudding user response:

Isn't the scanf should return 0.0 if I input not a valid double?

No, the specification of scanf does not say it does that.

In the 2018 C standard, clause 7.21.6.2 paragraph 4 says “… if a directive fails (as detailed below), the function returns.” It does not say any value, zero or otherwise, is put into the object being worked on.

To know whether a conversion succeeded, you should check the return value of the function. Do not just call scanf as a bare call. Either assign the return value to an int or test it in a condition.

Paragraph 16 says “The fscanf function returns the value of the macro EOF if an input failure occurs before the first conversion (if any) has completed. Otherwise, the function returns the number of input items assigned…” Thus, if you are expecting one item to be assigned normally, you should test whether the return value is one. (You can additionally test whether it is EOF to indicate some input failure occurred and, when reading multiple items at once, can test to see how many were assigned.)

Clause 7.21.6.2 is for fscanf, but it applies to scanf because clause 7.21.6.4, about scanf, refers to 7.21.6.2.

  • Related