Thread: Data validation for floating point

  1. #1
    Registered User
    Join Date
    Mar 2012

    Data validation for floating point

    I'm trying to validate of the user input is a positive floating point value or not.

    When user input is negative, the error message kicks in correctly. But when the user input consists of letters or some other symbols aside from numbers, the error message loops perpetually.

    What'm I doing wrong?

        char AmtStr[99];
        int i, j, Done = 0, Count = 0;
        float Amt;
        while (Done == 0) {
            printf("  Amount you have ");
            j = scanf("%f", &Amt);
            if (j == 1 && Amt > 0) {
                printf("  Proceed.");
            else {
                printf("  Error.\n\n");
                j = '\0';
                Amt = '\0';

  2. #2
    Registered User TheBigH's Avatar
    Join Date
    May 2010
    Melbourne, Australia
    Maybe because you never set the "Done" variable to be anything other than zero.
    while(!asleep) {

  3. #3
    Registered User
    Join Date
    Mar 2012
    Even if I set Done = 1 right after printing "Error", same thing happens.

    Solved! I just stuck a getchar(); right under j = scanf("%f", &Amt);.

    But why did it loop in the first place?
    Last edited by Jyqft; 03-25-2012 at 03:37 AM.

  4. #4
    and the hat of int overfl Salem's Avatar
    Join Date
    Aug 2001
    The edge of the known universe
    > j = scanf("%f", &Amt);
    If j is zero (or EOF), indicating no conversion took place, then Amt will be whatever undefined value was there from last time.

    > Amt = '\0';
    Whilst this works, it sends the wrong stylistic message to the user. '\0' is used in the context of characters.
    If you dance barefoot on the broken glass of undefined behaviour, you've got to expect the occasional cut.
    If at first you don't succeed, try writing your phone number on the exam paper.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. file operation for floating point data for window OS
    By saya407 in forum C Programming
    Replies: 7
    Last Post: 01-31-2012, 05:02 PM
  2. Floating point
    By anirban in forum C Programming
    Replies: 4
    Last Post: 08-16-2007, 07:11 AM
  3. Floating-Point (BCD)
    By zx-1 in forum C Programming
    Replies: 1
    Last Post: 10-15-2004, 01:11 AM
  4. fixed point / floating point
    By confuted in forum Game Programming
    Replies: 4
    Last Post: 08-13-2002, 01:25 PM
  5. Floating point faster than fixed-point
    By VirtualAce in forum A Brief History of
    Replies: 5
    Last Post: 11-08-2001, 11:34 PM