How can I get a safe input of integer (especially, positive number) using scanf
or gets
? I've tried several solutions and each solution had some problems.
1. Using getchar()
to remove string inputs
int safeInput() {
int input;
scanf("%d", &input);
while(getchar() != '\n');
return input;
}
This method effectively handles string inputs, however, if strings such as 3a
are inputted, the value of input
becomes 3
, which is not a true exception handle.
2. Retrieving input as a string then converting to integer value.
int safeInput() {
char[200] input, safe_input;
gets(input);
// I know about the security issue about gets - but it's not the point.
int i = 0;
while (1) {
if (input[i] >= 48 && input[i] <= 57) safe_input[i] = input[i];
else break;
i++;
}
return atoi(safe_input);
}
This method has problem that it cannot handle if string that has longer length than allocated to input
was inputted.
3. What if defining a string using pointer?
I concerned about defining input
by pointer, like char *input;
. However, once I executed gets(input)
(or scanf("%s", input)
), it raised runtime-error.
So what is a proper way to retrieve an integer value from console window using scanf
or gets
?