Thread: Validating Numbers only

  1. #1
    Registered User
    Join Date
    Dec 2004
    Posts
    3

    Validating Numbers only

    Hey Guys,

    I'm new to the C language.

    I'm trying to validate numbers only when you take input from the user. I don't want to accept alpha characters in there. But i can't figure it out. Here's my code.

    /*Currency Conversion Program*/

    #include<stdio.h>
    #include<ctype.h>
    main()
    {
    /*intergers declared*/
    float pesos = 11.3896, canadad = 1.18503, dem = 1.49923;
    float francs = 5.02760, aud = 1.27688;
    float america, mexico, canada, germany, france, australia;
    char dummy;

    /*requests input from user*/
    printf("\nCurrency Conversion\n");
    printf("\nPlease Enter US Dollars to be Converted: $");
    scanf(" %f", &america);

    /*loops statements if condition is met*/
    while(america<= 0)
    {
    printf("\nPlease insert a valid number entry > 0: $");
    scanf(" %f", &america);
    }

    /*Hard Coded Equations*/
    mexico = america * pesos;
    canada = america * canadad;
    germany = america * dem;
    france = america * francs;
    australia = america * aud;

    /*US Dollars Displayed and Converted According to Country*/
    printf("\n-----------------------------\n");
    printf("US Dollars Entered: $%.2f\n", america);
    printf("-----------------------------\n");
    printf("\nConverted Currency by Country:\n\n");
    printf("Mexico's Pesos: %.2f\n", mexico);
    printf("Canada's Dollars: %.2f\n", canada);
    printf("Germany's Marks: %.2f\n", germany);
    printf("France's Francs: %.2f\n", france);
    printf("Australia's Dollars: %.2f\n", australia);

    /*Requests user to end program*/
    printf("\nPress enter to exit: ");
    scanf("%c", dummy);

    return 0;

    }

  2. #2
    and the hat of int overfl Salem's Avatar
    Join Date
    Aug 2001
    Location
    The edge of the known universe
    Posts
    39,659
    Please use [code][/code]Tags

  3. #3
    Registered User
    Join Date
    Dec 2004
    Posts
    3
    sorry about that guys. Please help me figure out how to accept numbers only.

    Code:
    /*Currency Conversion Program*/
    
    #include<stdio.h>
    #include<ctype.h>
    main()
    {
       /*intergers declared*/
       float pesos = 11.3896, canadad = 1.18503, dem = 1.49923;
       float francs = 5.02760, aud = 1.27688;
       float america, mexico, canada, germany, france, australia;
       char dummy;
    
       /*requests input from user*/
       printf("\nCurrency Conversion\n");
       printf("\nPlease Enter US Dollars to be Converted: $");
       scanf(" %f", &america);
    
       /*loops statements if condition is met*/ 
       while(america<= 0)
       {
           printf("\nPlease insert a valid number entry > 0: $");
           scanf(" %f", &america); 
       }
    
       /*Hard Coded Equations*/
       mexico = america * pesos;
       canada = america * canadad;
       germany = america * dem;
       france = america * francs;
       australia = america * aud;
    
       /*US Dollars Displayed and Converted According to Country*/
       printf("\n-----------------------------\n");
       printf("US Dollars Entered: $%.2f\n", america);
       printf("-----------------------------\n");
       printf("\nConverted Currency by Country:\n\n");
       printf("Mexico's Pesos:      %.2f\n", mexico);
       printf("Canada's Dollars:    %.2f\n", canada);
       printf("Germany's Marks:     %.2f\n", germany);
       printf("France's Francs:     %.2f\n", france);
       printf("Australia's Dollars: %.2f\n", australia);
    
       /*Requests user to end program*/
       printf("\nPress enter to exit: ");
       scanf("%c", dummy);
    
       return 0;
    
    }

  4. #4
    Software Developer jverkoey's Avatar
    Join Date
    Feb 2003
    Location
    New York
    Posts
    1,905
    I'm not going to give you code, but I'll give you advice:

    Try looking in to the isdigit function and get the input as a string instead of a number. This way you can check to see if there are any invalid letters in there (don't forget that a . is a valid letter in a floating-point number!!)

  5. #5
    Registered User
    Join Date
    Dec 2004
    Posts
    3
    does that means using getchar() instead of scanf()? also how would i convert the string number back into a float variable?

  6. #6
    Hello,

    What jverkoey was trying to accomplish is to help you understand how this concept works. The overall concept is not hard, and you can do it if you set your mind to it.

    For example, I will list the concept idea and let you build from it:
    • Retreive input as string. [View stdio reference]
    • Walk along string
    • Look for digits [consider isdigit()], periods, and other valid floating type vars
    • If not found, your input is not a floating type variable

    Quite simple.

    - Stack Overflow
    Segmentation Fault: I am an error in which a running program attempts to access memory not allocated to it and core dumps with a segmentation violation error. This is often caused by improper usage of pointers, attempts to access a non-existent or read-only physical memory address, re-use of memory if freed within the same scope, de-referencing a null pointer, or (in C) inadvertently using a non-pointer variable as a pointer.

  7. #7
    Gawking at stupidity
    Join Date
    Jul 2004
    Location
    Oregon, USA
    Posts
    3,218
    Quote Originally Posted by shacapoo
    how would i convert the string number back into a float variable?
    Look at the atof() function.
    If you understand what you're doing, you're not learning anything.

  8. #8
    Registered User
    Join Date
    Sep 2004
    Posts
    44
    This seems to work pretty well, I adapted it from some code in the FAQ here: http://faq.cprogramming.com/cgi-bin/...&id=1043284385

    Code:
    #include <stdio.h>
    #include <conio.h>
    #include <stdlib.h>
    
    #define FALSE 0
    #define TRUE ~FALSE
    
    float getfloat(int *error);
    
    int main(void)
    {
        float num;
        int err = 0;
    
        printf("Enter a float: ");
        num = getfloat(&err);
        if(err == FALSE)
        {
            printf("The number you entered is %f \n", num);
        }
        else
        {
            printf("Invalid float! \n");
        }
        printf("\nPress any key to continue...");
        getch();
        return(0);
    }
    
    float getfloat(int *error)
    {
        char buf[BUFSIZ];
        char *p;
        double n;
    
        fflush(stdin);    /* Visual C extension to standard C,
                             not standard C. Check your compiler
                             documentation. */
        fgets(buf, sizeof(buf), stdin);
        n = strtod(buf, &p);
        if( buf[0] != '\n' && (*p == '\n' || *p == '\0') )
        {
            *error = FALSE;
        }
        else
        {
            *error = TRUE;
        }
        return( (float) n );
    }
    Last edited by n7yap; 12-10-2004 at 04:35 PM.

  9. #9
    Registered User
    Join Date
    Nov 2004
    Location
    USA
    Posts
    516
    whenever you take in input from the user,check for ascii values other than those of the digits and dots that you want to accept.if the ascii values are not the same as the ones for the digits,print an error else continue.
    ciao

  10. #10
    Just Lurking Dave_Sinkula's Avatar
    Join Date
    Oct 2002
    Posts
    5,005
    Quote Originally Posted by n7yap
    This seems to work pretty well, I adapted it from some code in the FAQ here: http://faq.cprogramming.com/cgi-bin/...&id=1043284385
    You missed this FAQ:
    FAQ > Explanations of... > Why fflush(stdin) is wrong
    [edit]Or http://www.eskimo.com/~scs/C-faq/q9.1.html
    Last edited by Dave_Sinkula; 12-09-2004 at 11:03 PM.
    7. It is easier to write an incorrect program than understand a correct one.
    40. There are two ways to write error-free programs; only the third one works.*

  11. #11
    Registered User
    Join Date
    Sep 2004
    Posts
    44
    I knew somebody was going to say that. I read that FAQ, and I've read about it elsewhere. I use Visual C++ 2003. If you look at MSDN 'fflush' works fine with 'stdin'. If you use a different compiler, you need to look at the documentation for your compiler as 'fflush(stdin)' is an extension to standard C.

  12. #12
    ATH0 quzah's Avatar
    Join Date
    Oct 2001
    Posts
    14,826
    Or you can just write code that conforms to the Standard, and which doesn't invoke undefined behavior and not have to worry about it.
    Code:
    while( fgetc( stdin ) != '\n' );
    Gee, that was hard.

    Quzah.
    Hope is the first step on the road to disappointment.

  13. #13
    Registered User
    Join Date
    Sep 2004
    Posts
    44
    quzah,

    You're right, for posting on this board, I shouldn't have used something that doesn't conform to standard C. If your compiler doesn't support 'fflush(stdin)' replace it with quzah's code.
    Last edited by n7yap; 12-10-2004 at 12:15 AM.

  14. #14
    Registered User
    Join Date
    Sep 2004
    Posts
    44
    What do you all think about using 'rewind(stdin)' to clear the keyboard buffer? Visual C supports it.

  15. #15
    Just Lurking Dave_Sinkula's Avatar
    Join Date
    Oct 2002
    Posts
    5,005
    Quote Originally Posted by n7yap
    What do you all think about using 'rewind(stdin)' to clear the keyboard buffer? Visual C supports it.
    There are issues if the input is redirected.
    7. It is easier to write an incorrect program than understand a correct one.
    40. There are two ways to write error-free programs; only the third one works.*

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Comparing numbers to a list of numbers held in a text file
    By jmajeremy in forum C++ Programming
    Replies: 3
    Last Post: 11-06-2006, 07:56 AM
  2. Logical errors with seach function
    By Taka in forum C Programming
    Replies: 4
    Last Post: 09-18-2006, 05:20 AM
  3. Adding Line numbers in Word
    By Mister C in forum A Brief History of Cprogramming.com
    Replies: 24
    Last Post: 06-24-2004, 08:45 PM
  4. the definition of a mathematical "average" or "mean"
    By DavidP in forum A Brief History of Cprogramming.com
    Replies: 7
    Last Post: 12-03-2002, 11:15 AM
  5. A (complex) question on numbers
    By Unregistered in forum C++ Programming
    Replies: 8
    Last Post: 02-03-2002, 06:38 PM