I read that the scanf function is not safe. I made an attempt for a getInt(), but I'm not happy about it. I have to give two arguments: the max value and the max length of the number (I mean the max number of characters in the string). I'm not able to extract this maxLength from the max value:
It's kinda messy, but I don't see an alternative... Any suggestions?Code:int getInt(int max, int maxLength){ char input[maxLength]; char c; int i; printf("Enter an integer: "); for (i = 0;(c = getchar())!='\n';++i){ if (i < maxLength-1){ if (!isdigit(c) && (c !='-')){ printf("Number contains non-digit characters. Exiting."); exit(0); } input[i] = c; } else { printf("Number was too long. Exiting"); exit(0); } } int result = atoi(input); if (result <= max){ return result; } else { return -1; } }