Search code examples
cscanffflush

scanf for reading float numbers doesn't work as expected


I am in a programming class since 2 weeks and have some trouble with scanning keyboard input an assigning it to a variable in C.

#include <stdio.h>
#include <stdlib.h>

int main()

{
  float creditSum, interestRate, repayment;

  system("clear");

  printf("\n please enter the total Credit sum: ");
  scanf("%.2f", &creditSum);
  printf("\n Please enter the interest rate: ");
  scanf("%.2f", &interestRate);
  printf("\n Please enter the monthly repayment amount: ");
  scanf("%.2f", &repayment);

  printf("\n\n %.2f | %.2f | %.2f\n\n", creditSum, interestRate, repayment);


   return 0;
}

I can compile an run the program but am getting

user@db10:~/$ ./credit 

 please enter the total Credit sum: 100

 Please enter the interest rate: 
 Please enter the monthly repayment amount: 

 0.00 | 0.00 | 0.00

So I still can enter the first of 3 values, which is not assigned to the variable as planned.

The course teacher has everybody add a fflush(stdin) before the scanf() on windows machines but this does not work for me (in a linux environment).

I have seen some issues here dealing with the fflush on linux issue, but can't really apply anything successfully for my case (which may be due to me being a complete novice in coding).

Can anyone help here?

The teacher takes a "can't troubleshoot Linux problems as Windows is the OS of choice" approach, so there is not help to be expected from that side.


Solution

  • The scanf catches the input format that is not expected.

    The right code should be this:

    #include <stdio.h>
    #include <stdlib.h>
    
    int main()
    
    {
      float creditSum, interestRate, repayment;
    
      system("clear");
      
    
      printf("\n please enter the total Credit sum: ");
      if(scanf("%f", &creditSum)!= 1) return -1;
      printf("\n Please enter the interest rate: ");
      if(scanf("%f", &interestRate)!= 1) return -1;
      printf("\n Please enter the monthly repayment amount: ");
      if(scanf("%f", &repayment)!= 1) return -1;
    
      printf("\n\n %.2f | %.2f | %.2f\n\n", creditSum, interestRate, repayment);
    
    
       return 0;
    }
    

    You probably don't want to capture only 2 decimal of the float. You want take the float number and then print it with only 2 decimal.

    In any case is important to check the return value of the scanf:

    On success, the function returns the number of items of the argument list successfully filled. This count can match the expected number of items or be less (even zero) due to a matching failure, a reading error, or the reach of the end-of-file.

    because it can avoid bugs on code.