Howdy, Stranger!

It looks like you're new here. If you want to get involved, click one of these buttons!

Categories

Check user input for valid entry

This is for C programming.

I posted a message earlier on this but the response did not work. I need to allow the user to enter a number and nothing else. I want them to only be able to enter positive numbers. They are entering a dollar amount. This could be 10.37 or 44 or whatever. It just has to be a valid currency amount. No negative numbers and no letters. If they enter those it should say invalid entry please try again. Can anyone help. The simpler the better here as I am quite new.

Comments

  • Griz803Griz803 Member Posts: 100
    This isn't complete, but it validates as positive numbers only. I'll leave the letters for you to solve.
    [CODE]
    #include
    #include
    #include
    #include

    float get_amount(void)
    {
    float temp;

    printf("
    Enter an Amount : ");
    scanf("%f", &temp);
    fflush(stdin);
    if(temp < 0)
    {
    printf("Invalid Input, hit any key to re-enter.");
    getch();
    clrscr();
    temp = get_amount();
    }

    return(temp);

    }

    int main(void)

    {
    float some_num;

    some_num = get_amount();
    getch();
    printf("some_num = %f", some_num);
    return 0;

    }
    [/CODE]
    This compiles and runs on Borland 4.5. Hint: check out ctype.h for an easy character check. Notice the useful recursion in get_amount. Hope this helps.

Sign In or Register to comment.