'scanf in C leading to infinite loop [duplicate]
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;
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
