How can I use a variable to specify the max number of chars scanf() should read in?
For example using printf() you can use the * like so
Kernighan and Pike recommend using snprintf() to create the format string. I developed this idea into a method that safely reads strings:
void scan_string(char * buffer, unsigned length) {
char format[12]; // Support max int value for the format %s
snprintf(format, sizeof(format), "%%%ds", length - 1); // Generate format
scanf(format, buffer);
}
int main() {
char string[5];
scan_string(string, sizeof(string));
printf("%s\n", string);
}