check for numbers

This is a discussion on check for numbers within the C Programming forums, part of the General Programming Boards category; I want to check that a user inputs only numbers or space. If characters are inputed then print an error. ...

  1. #1
    Unregistered
    Guest

    check for numbers

    I want to check that a user inputs only numbers or space.
    If characters are inputed then print an error.

    I started doing it with these lines of code but I am reallu stuck now....any suggestion on how to proceed.

    I just started learning C.

    Here is what I have:

    int main(void)
    {
    char line[80];
    char n;

    for(;
    {
    gets(line);
    if(feof(stdin)) break;
    n=atoi(line);
    printf("%d\n", n);
    }
    return 0;
    }

  2. #2
    and the hat of wrongness Salem's Avatar
    Join Date
    Aug 2001
    Location
    The edge of the known universe
    Posts
    32,755
    > I want to check that a user inputs only numbers or space.
    Use isdigit() and isspace() to test each char in the buffer (using say a for loop)

  3. #3
    Registered User
    Join Date
    Jan 2002
    Posts
    16

    Re: check for numbers


    if(feof(stdin)) break;
    Don't know if you can test for eof on stdin, as unless re-directed using freopen(), this is the keyboard stream. No doubt one of the Guru's can put us straight on this.

    Cheers,
    foffo
    'C that?... I felt nowt' - The Original Foffo Spearjig and his hard dog. The Tube TV show, sometime in the 80's

  4. #4
    Im back! shaik786's Avatar
    Join Date
    Jun 2002
    Location
    Bangalore, India
    Posts
    345
    >Don't know if you can test for eof on stdin, as unless re-directed using freopen(), this is the keyboard stream.
    'stdin' is just another file as is any other file opened for reading. The rules of EOF which apply on any other file apply on this file stream as well. The only difference regarding the EOF might be the ASCII value given to it on each system. In most of the UNIX systems, it's CTRL+D, while in DOS it's CTRL+Z

  5. #5
    Code Goddess Prelude's Avatar
    Join Date
    Sep 2001
    Posts
    9,796
    >I started doing it with these lines of code but I am reallu stuck
    >now....any suggestion on how to proceed.
    Try a board search for integer validation, I've posted code for this several times and it's been referred to quite a bit.

    -Prelude
    My best code is written with the delete key.

  6. #6
    Unregistered
    Guest

    Here...

    I just did that a few days ago, this involves floating points,
    just tweak the following code to do what you want it to do...

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

    void checknumber(char string[10])
    {
    int i;

    for (i=0; string[i]; i++)
    {
    if(string[0] == NULL || string[i]<45 || string[i] == 47 || string[i]>57)
    {
    exit(1);
    }

    if(i>0 && string[i] == 45)
    {
    exit(1);
    }
    }
    }


    main()
    {
    char string[10];


    float num;

    do
    {
    printf("Enter number : ");
    gets(string);

    checknumber(string);
    num = atof(string);

    }

    getchar();

    }



    http://mahurshi.tripod.com/mainframes.htm

  7. #7
    Registered User pinko_liberal's Avatar
    Join Date
    Oct 2001
    Posts
    284

    Re: check for numbers

    Code:
    int main(void)
    {
    char line[80];
    char n;
    
    for(;;)
    {  
    	gets(line);
                        if(feof(stdin)) break;			
     	n=atoi(line);
    	printf("%d\n", n);
    }
    	return 0;
    }
    I think you are making a subtle mistake in the program , suppose stdin contains only a single character 1 and the file ends , or it contains 1 followed by a '\n' and then the file ends , your program will simply not process the line

  8. #8
    Code Goddess Prelude's Avatar
    Join Date
    Sep 2001
    Posts
    9,796
    Code:
    void checknumber(char string[]) 
    { 
      int i; 
    
      for (i=0; string[i] != '\0'; i++) 
      { 
        if(string[0] == '\0' || string[i] < 45 || string[i] == 47 || string[i] > 57) 
        { 
          exit(1); 
        } 
    
        if(i>0 && string[i] == 45) 
        { 
          exit(1); 
        } 
      } 
    }
    And this function is useful...how?

    Code:
    main() 
    { 
      char string[10]; 
      float num; 
      do 
      { 
        printf("Enter number : "); 
        gets(string); 
        checknumber(string); 
        num = atof(string); 
      } 
      getchar(); 
    }
    That sure is a lot of errors for one little function. main returns an int, anything else and you'll be sorry. Identifiers starting with str are reserved, gets should never be used, num is a float and atof returns a double, a do..while loop should actually have the while part included or it won't work, and checknumber does nothing except quit the program. How useless is that?

    How about something more along the lines of this:
    Code:
    #include <stdio.h>
    #include <stdlib.h>
    #include <string.h>
    #include <ctype.h>
    
    /* Just fooling around, int works fine too */
    enum ISVAL { VALID, INVALID };
    typedef enum ISVAL val_t;
    
    static val_t checknumber ( char *astr )
    {
      while ( *astr != '\0' )
        if ( !isdigit ( *astr++ ) )
          return INVALID;
      return VALID;
    }
    
    int main(void)
    {
      char astr[10];
      if ( fgets ( astr, 10, stdin ) != NULL ) {
        if ( astr[strlen(astr)-1] == '\n' )
          astr[strlen(astr)-1] = '\0';
        if ( checknumber ( astr ) == INVALID )
          printf ( "Invalid integer\n" );
        else
          printf ( "Your number is %d\n", atoi ( astr ) );
      }
      return 0;
    }
    -Prelude
    My best code is written with the delete key.

  9. #9
    Unregistered
    Guest
    The do while loop got cut while I was pasting the code...


    string is not a reserved keyword

    the program works fine for me

    no one said they'll kill me if i use gets

    sure main returns an int, but that's no freakin error

    checknumber quits the program if there are characters
    and not numbers in the inputted string... if they're numbers,
    it saves them into a float variable.

    how useless is that ?
    frankly, you're an egoistic idiot who'll never grow up
    because you never want to appreciate things.

    See the whole code below and if checknumber does NOTHING
    but quit the program, you can pat yourself.
    If it works, go spank yourself and don't talk again!


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

    void checknumber(char string[10])
    {
    int i;

    for (i=0; string[i]; i++)
    {
    if(string[0] == NULL || string[i]<45 || string[i] == 47 || string[i]>57)
    {
    exit(1);
    }

    if(i>0 && string[i] == 45)
    {
    exit(1);
    }
    }
    }


    main()
    {
    char string1[10];
    char string2[10];

    float num1, num2;


    do
    {
    printf("Enter number1 : ");
    gets(string1);

    checknumber(string1);
    num1 = atof(string1);

    printf("Enter number2 : ");
    gets(string2);

    checknumber(string2);
    num2 = atof(string2);

    printf("(%f - %f)/(%f * %f) = %f\n", num1, num2, num1, num2, (num1-num2)/(num1*num2));
    } while (1==1);

    getchar();

    }

  10. #10
    Shroeder
    Guest

    Thumbs down Ha ha

    as prelude said, str**** is also a reserved keyword...
    (ha ha,... sorry, couldn't stop laughing at the mountain
    of arrogance.)

  11. #11
    Code Goddess Prelude's Avatar
    Join Date
    Sep 2001
    Posts
    9,796
    >The do while loop got cut while I was pasting the code...
    Understandable.

    >string is not a reserved keyword
    Prove it, I can most certainly prove that it is.

    >the program works fine for me
    Famous last words. Guess what? Not everyone uses the exact same computer and programs that you do. Just because it works for you doesn't mean it works everywhere and anyone who believes otherwise shouldn't be programming anything important.

    >no one said they'll kill me if i use gets
    No one will kill you if you use gets, you'll get yelled at a lot though because gets is very unsafe.

    >sure main returns an int, but that's no freakin error
    Are you sure? If you don't return an int then what does the calling function recieve from your program? Undefined behavior is most definitely an error. But if you'd like you can try to prove me wrong.

    >how useless is that ?
    In your kiddie classroom it's probably pretty good (taking the quality of most teachers into account of course), but in my world terminating a program without attempting to recover from the error is very bad, especially with something simple like user input.

    >frankly, you're an egoistic idiot who'll never grow up
    >because you never want to appreciate things.
    Slightly egotistical, yes. I'll grant you that. But don't think I'm an idiot just because I found problems with your "perfect" code. Why don't you try listening and learning instead of complaining, it's far more productive. As for appreciating things, I can appreciate bad code as much as anyone. As long as it isn't used in a real application and only for fun. Your code is completely different because you believe it to be good and you won't hear any comments to the contrary.

    >See the whole code below
    I saw it and told you what was wrong, I gave you an alternative that was much better. What do you want me to do?

    >and don't talk again!
    Out of this entire post, I laughed at this the hardest.

    I didn't say that your program quits every time, but I can see how you could have viewed it that way. What I meant was that terminating a program on some silly little error is useless. If you think that kind of code is used anywhere outside of a classroom then I really hope you don't go to work for a nuclear power plant or hospital.

    If you can't accept constructive criticism then you'd best quit now, because you will be wrong a great deal when learning to program. Though if you still think I'm an idiot, go searching around for proof that I'm in the wrong. I can guarantee that you won't find anything valid.

    -Prelude
    My best code is written with the delete key.

  12. #12
    Unregistered
    Guest
    >>and checknumber does nothing except quit the program. How useless is that?


    >>I didn't say that your program quits every time


    ^^^^ TWO CONTRADICTORY STATEMENTS ABOVE ^^^^


    >>In your kiddie classroom

    Assumption that I am a kid, and i am a beginner and that
    my teachers are of poor quality displays your egoistic behaviour.

    Sure I am a beginner, sure you know more than me, but
    I dont go to a classroom to learn C. (maybe that's the
    reason why you can beat me in writing code)

    and you need not assume that teachers with lousy
    students are of poor quality (assuming that i am a lousy
    student and that i am taking a c/c++ course)

    that's a clear indication of arrogance, which can not
    be cured by anyone else but oneself.


    But when you're talking about ego, and "constructive criticism"
    with statements like

    >>In your kiddie classroom it's probably pretty good (taking the quality of most teachers into account of course),

    and

    >>I really hope you don't go to work for a nuclear power plant or hospital.


    I have nothing else to say, you have to understand it yourself.
    I can't teach values to loser types.

  13. #13
    Proctor
    Guest

    string..

    string ain't a reserved word, mama

  14. #14
    Code Goddess Prelude's Avatar
    Join Date
    Sep 2001
    Posts
    9,796
    >^^^^ TWO CONTRADICTORY STATEMENTS ABOVE ^^^^
    A case of listening to what I meant and not what I said , why are you so confrontational?

    >Assumption that I am a kid, and i am a beginner
    I have no idea what age you are nor does it matter. I know that you are a beginner by looking at your code. By kiddie I meant inexperienced and (possibly, but not always) willfully ignorant. Simply not knowing is excusable since everyone begins somewhere, but what you have shown thus far is a complete lack of understanding and no desire at all to improve yourself. All you seem to want to do is flame me for correcting you on several points.

    >But when you're talking about ego, and "constructive criticism"
    >with statements like
    I treat you with the same amount of respect you have shown me, please, talk more about values. Let's also consider that it was you who started throwing flames, I only responded in kind.

    >string ain't a reserved word, mama
    Incorrect:
    Code:
    /* Excerpt from the ISO C standard */
    
    7.26 Future library directions
    1 The following names are grouped under individual headers for convenience. All external
    names described below are reserved no matter what headers are included by the program.
    .
    .
    .
    7.26.11 String handling <string.h>
    1 Function names that begin with str, mem, or wcs and a lowercase letter may be added
    to the declarations in the <string.h> header.
    There's a rule about correcting someone. Make sure you're right before saying anything. There are people less kind than I who would gladly slam you down hard and try to humiliate you for everyone to see.

    -Prelude
    My best code is written with the delete key.

  15. #15
    ATH0 quzah's Avatar
    Join Date
    Oct 2001
    Posts
    14,826
    Originally posted by Unregistered
    >>and checknumber does nothing except quit the program. How useless is that?


    >>I didn't say that your program quits every time


    ^^^^ TWO CONTRADICTORY STATEMENTS ABOVE ^^^^
    You are intentionally missing the point. Why the **** would you want your program to just terminate on an incorrect entry? Have you ever heard of "Prompt the user to enter the number correctly."? Apparently not.






    Originally posted by Unregistered
    >>In your kiddie classroom

    Assumption that I am a kid, and i am a beginner and that
    my teachers are of poor quality displays your egoistic behaviour.

    Sure I am a beginner, sure you know more than me, but
    I dont go to a classroom to learn C. (maybe that's the
    reason why you can beat me in writing code)
    The object of the board isn't to "beat you in writing code", it's to help dumb asses like you improve their coding ability.

    You post code. I show you a way to improve it. You either:

    a) stick you head up your ass and come back all hostile, mad that your code isn't "a gift from god"

    b) realize that most people with a few thousand posts here actually know what the **** they're talking about, and say, "Ah, I see how it's possible for me to have made an error." "I see what you mean." "I don't see what you mean, can you clarify?"

    You decide. Oh, wait, you have.


    Originally posted by Unregistered
    and you need not assume that teachers with lousy
    students are of poor quality (assuming that i am a lousy
    student and that i am taking a c/c++ course)
    Actually, from the people that post here, that are taking classes, who actually say "MY TEACHER DOESN'T KNOW WHAT THEY'RE TALKING ABOUT.", I'd say it's safe for me to make that assumption.

    I'd say that from the number of "professional" C / C++ books where they teach that "void main" is OK, that you don't have to return an integer, that, yeah, there are stupid "professional" authors, and as such, simply ignorant teachers.

    Yeah, I'd say it's safe for me to make that assumption.

    I've been here for ~2 years or so, helping people with C off and on. I've seen countless people complain about their teachers not knowing what they're talking about, so again, yeah, I'd say it's safe for me to make this assumption.

    You've been here how long? You're an authority on teachers why exactly?


    Originally posted by Unregistered
    that's a clear indication of arrogance, which can not
    be cured by anyone else but oneself.


    But when you're talking about ego, and "constructive criticism"
    with statements like

    >>In your kiddie classroom it's probably pretty good (taking the quality of most teachers into account of course),

    and

    >>I really hope you don't go to work for a nuclear power plant or hospital.
    See above. You are just miffed because the code that you wrote to try and help someone was shown to have errors and potential unwanted side effects.

    If you don't like the problems with your code, shut up and fix them.

    Originally posted by Unregistered
    I have nothing else to say, you have to understand it yourself.
    I can't teach values to loser types.
    It is to laugh.

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

Page 1 of 2 12 LastLast
Popular pages Recent additions subscribe to a feed

Similar Threads

  1. BN_CLICKED, change button style
    By bennyandthejets in forum Windows Programming
    Replies: 13
    Last Post: 07-06-2010, 12:42 AM
  2. How can i check a directory for certain files?
    By patrioticpar883 in forum C++ Programming
    Replies: 13
    Last Post: 02-01-2008, 05:27 PM
  3. how to check input is decimal or not?
    By kalamram in forum C Programming
    Replies: 3
    Last Post: 08-31-2007, 08:07 PM
  4. Please check this loop
    By Daesom in forum C++ Programming
    Replies: 13
    Last Post: 11-02-2006, 01:52 AM
  5. how to check for end of line in a text file
    By anooj123 in forum C++ Programming
    Replies: 6
    Last Post: 10-25-2002, 12:21 AM

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21