RocktheFries
RocktheFries

Reputation: 221

Looking at user input to see if it is a float, always coming back as true

I trying to prompt the user fora number, and scan it to see if it is a float. Even when entering a number without a decimal it is coming back saying it is a float. The function should return 1 if the input is a float, and 0 if its not. I have a feeling its an issue with my function logic. Any help would be appreciated. Thanks!

#include <stdio.h>   //including for the use of printf
#pragma warning(disable: 4996)      // turn off warning about sscanf()

/* == FUNCTION PROTOTYPES == */
double getDouble(double *pNumber);
double *pNumber = NULL;

int main(void)
{   
    double returnedValue = 0;
    double userInput = 0;
    int runOnce = 0;

    printf("Please Enter a float:");
    userInput = getDouble(&returnedValue);

    while (runOnce == 0)
    {
        if (userInput == 1)
        {
            printf("Your number is a valid float!\n");
            printf("%lf", returnedValue);
        }

        else
        {
            printf("Your number is not a float!\n");
        }

        printf("Press ENTER key to Continue\n");
        getchar();
    }
}



#pragma warning(disable: 4996)
double getDouble(double *pNumber)
{
    char record[121] = { 0 }; /* record stores the string from the user*/
    double number = 0;

    /* fgets() - a function that can be called in order to read user input from the keyboard */
    fgets(record, 121, stdin);

    if (scanf("%lf", &number) == 1)
    {
        *pNumber = number;
        return 1;
    }
    else
    {
        return 0;
    }
}

Upvotes: 2

Views: 42

Answers (1)

John Kugelman
John Kugelman

Reputation: 361585

You're calling both fgets() and scanf(). Use one or the other but not both. If you're going to use fgets() then use sscanf() to parse its result.

Upvotes: 1

Related Questions