Thread: Problem with function for safe input.

Threaded View

Previous Post Previous Post   Next Post Next Post
  1. #1
    Registered User
    Join Date
    Jan 2009
    Posts
    1,485

    Problem with function for safe input.

    I'm trying to validate the input and only accept numeric entries at the set length. I'm getting weird behaviour if characters are inputed though. The while loop seems to execute two rounds per character. Can anyone see what the problem might be.

    Code:
    #include <stdio.h>
    #include <stdlib.h>
    #include <string.h>
    #include <stdbool.h>
    
    #define LENGTH 4
    #define ZERO 48
    #define NINE 57
    
    int main()
    {
            int stringLength = LENGTH + 4;
            char string[stringLength];
            unsigned int n, i = 0;
            bool valid;
    
            do{
                    valid = true;
                    printf("Enter a %d digit number: ", LENGTH);
    
                    for(i = 0; i < LENGTH; i++){
                            string[i] = getchar();
                            if(string[i] < ZERO || string[i] > NINE){
                                    valid = false;
                                    break;
                            }
                    }
            }while(!valid);
            string[i] = 0;
    
            n = strtol(string, NULL, 0);
    
            printf("%d\n", n);
    
            return 0;
    }

    Also, are there some good guidlines to be found somewhere for making generic safe input functions?
    Last edited by Subsonics; 11-01-2009 at 10:43 AM.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Screwy Linker Error - VC2005
    By Tonto in forum C++ Programming
    Replies: 5
    Last Post: 06-19-2007, 02:39 PM
  2. Replies: 28
    Last Post: 07-16-2006, 11:35 PM
  3. c++ linking problem for x11
    By kron in forum Linux Programming
    Replies: 1
    Last Post: 11-19-2004, 10:18 AM
  4. Custom Made Safe Input Function
    By Beast() in forum C Programming
    Replies: 6
    Last Post: 08-21-2004, 10:19 PM
  5. Problem using "cin" in a thread function?
    By Fossil in forum Windows Programming
    Replies: 4
    Last Post: 11-24-2003, 09:08 PM