title: Range of Input Loop in C
body: <p>I've been trying to find out how to make a program that loops while the input is out of range and which rejects invalid input like alphabets or nothing input into the program.  I found one solution, but it uses a range of numbers  1-99 as accepted values. I want to be able make the range 1-20 or then 1-any specified range, but when I tried to modify the program, it stops working properly. Does anyone know how to change this program so that the range is different (ex 1-20 or 1-30), but the program still works as it should, meaning it tells the user if the number out of range, if nothing is input, or if incorrect symbols are input. Also, if someone manages to do this, could you please explain to me what the logic behind it is?</p>
  
  <pre><code>#include "stdio.h"
  #include "string.h"
  
  int main() {
  
      printf("\nProgram Start.....\n\n");
  
      char userInput[64];
      int num = 0;
      char temp;
      size_t length = 0;
      int index = 0;
      int flag = 0;
      while( num == 0 ) {
  
          length = 0;
          flag = 0;
          num = 0;
  
          printf("Please enter a number 1 to 99:");
          fgets(userInput, 63, stdin);
          length = strlen(userInput);
  
          if( length &lt; 2 || length &gt; 3) {
              printf("Invalid strlen()\n");
              continue;
          }
  
          length--;
  
          for(index = 0; index &lt; length; ++index) {
              if(userInput[index] &lt; '0' || userInput[index] &gt; '9') {
                  flag = 1;
                  break;
              }
          }
  
          if( flag) {
              printf("Invalid character\n");
              continue;
          }
  
          if( sscanf(userInput, "%d", &amp;num) != 1) {
              printf("Invalid sscanf()\n");
              continue;
          }
  
          if( num &lt; 1 || num &gt; 99) {
              printf("Invalid range\n");
              continue;
          }
  
          printf("Number OK:%d\n",num);
      }
  
      printf("\nProgram Quit.....\n");
  
      return 0;
  }
  </code></pre>