Thread: Validating an Integer

Threaded View

Previous Post Previous Post   Next Post Next Post
  1. #1
    Registered User
    Join Date
    Mar 2022
    Posts
    1

    Question Validating an Integer

    Dear all,

    I am a total beginner to C - I've got some code that I'm trying to write that ensures you're entering an integer between 1 and 1000 inclusive. I want to verify the integer is the correct length (4), and that it is an integer.

    Code:
    void enterN(int *inputInteger)
    {
      char str[5] = { };
      int isValid = 0;
      while (isValid == 0) {
        scanf("%5s", str);
        if (strlen(str) > 4) {
          printf("Please enter a number within 1-1000: ");
          char c = 0;
          while ((c = getchar()) != '\n' && c != EOF);
    
        }
    
        char *endptr = NULL;
        *inputInteger = strtol(str, &endptr, 10);
        errno = 0;
    
        if (str == endptr) {
          printf("Not an integer.");
        }
    
        if (errno != 0) {
          printf("Not an integer, errored.\n");
        }
    
        if ((strtol(str, &endptr, 10) >= 1) && (strtol(str, &endptr, 10) <= 1000)) {
          isValid = 1;
        }
    
        else {
          printf("Something wrong with input");
          printf("%s", str);
        }
      }
      printf("%s", str);
    }
    Every time I test my program by typing values such as 11111, it throws up the else condition saying something is wrong, immediately after saying values are too long. I don't want two errors - I have a feeling I'm not flushing a buffer properly but I have no idea how to do this and what to change.

    Values like 111, and 1000 work.

    Could someone please help me edit my code to fix this? Thank you!
    Last edited by Salem; 03-01-2022 at 11:11 PM. Reason: Removed crayola

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Problem validating
    By Kinto in forum C++ Programming
    Replies: 6
    Last Post: 10-25-2009, 05:19 PM
  2. Validating time
    By csonx_p in forum C++ Programming
    Replies: 18
    Last Post: 01-11-2009, 09:34 AM
  3. Problems validating
    By ebenezum in forum C Programming
    Replies: 1
    Last Post: 05-18-2008, 12:01 PM
  4. Can someone help me with validating?
    By Maria Jordan in forum C Programming
    Replies: 5
    Last Post: 03-27-2005, 04:41 AM
  5. Validating Numbers only
    By shacapoo in forum C Programming
    Replies: 25
    Last Post: 12-11-2004, 11:13 PM

Tags for this Thread