Search code examples
crecursionscanffunction-definition

scanf in C leading to infinite loop


I am trying to write a simple c program that takes input using scanf, and ensures that this input is an integer. To do this I have written a recursive function, but the function goes into an infinite loop if I enter a non-integer character. I've attatched the code below.

#include <stdio.h>

int getInput() {
  int success = 0;
  int input;

  printf("Enter a positive integer: \n");
  success = scanf(" %d", &input);

  if (success == 0 || input < 0) {
    return getInput();
  }else return input;
}

Solution

  • The problem is that if a non-number is entered the input buffer contains a garbage. You need to clear the input buffer before trying to enter another number.

    Using your approach with the call of scanf the function can look for example the following way

    int getInput( void ) 
    {
        int input = 0;
    
        printf("Enter a positive integer: \n");
      
        if ( scanf( "%d", &input) != 1 )
        {
            scanf( "%*[^\n]" ); 
        }
    
        return input <= 0 ? getInput() : input;
    }
    

    Another more complex approach is to use the function fgets and strtol and check their results.