So I tasked myself to write a function, that:
- overwrites an int with a safe value (not return gibberish if the user decides to input char-s or anything bigger by absolute value than (2^31-1)
- if input exceeds (2^31 - 1) (meaning if the user inputs 8 or more digits) the int must be overwritten with the upper value
Here is the code:
void getSafeIntWithBoundaries(int *dest, int lo, int hi, const char *message);
bool anyChars(const char *input, int len);
int main() {
int x;
getSafeIntWithBoundaries(&x, 1, 10, "Enter an integer between 0 and 10.");
printf("x = %d\n", x);
return 0;
}
void getSafeIntWithBoundaries(int * dest, int lo, int hi, const char * message) {
char input[33];
while (1) {
puts(message);
fgets(input, 33, stdin);
int len = strlen(input);
if (input[len - 1] == '\n') { input[len - 1] = '\0'; }
--len;
if (bool reset = anyChars(input, len)) {
puts("Try again.");
continue;
}
else {
int ret;
if (strcmp("2147483648", input) < 0) {
*dest = hi;
return;
}
sscanf(input, "%d", &ret);
ret = ret > hi ? hi : ret;
ret = ret < lo ? lo : ret;
*dest = ret;
break;
}
}
}
bool anyChars(const char * input, int len) {
for(int i = 0; i < len; i++) {
if (!isdigit(input[i])) {
return true;
}
}
return false;
}
A few more notes:
- in
getSafeIntWithBoundaries(...)
I'm getting rid of the'\n'
, I'm changing it for a'\0'
, respectively decreasingint len;
which holds the length of the input. anyChars()
checks whether the input contains any non digitchar
. If it does, then the user has to re-enter. One of the problems is however that in case of failure, message needs to be printed out only once. If I input something ridiculously long, message will be printed multiple times. I don't know how to fix this.- the strcmp() bit checks if the user entered a number bigger than (2^31 - 1). If the user has, then the int must be overwritten with the high value and the function needs to end. Problem is however, if the user enters a very long number, the target int will be overwritten with the low boundary. I don't know how to fix that either.
2 ?s making sure the target int won't exceed its boundaries. I marked the parts that I can't figure out with bold, essentially that's the whole question.
Suggestions on improving the code are welcomed as well.