When using the scanf function, you can indicate the maximum number of characters to be read by placing a value before the type of the % specifier. For example:
char cadena[21]; // Último carácter reservado para '\0'
scanf("%20s", cadena);
In this way you avoid that more characters are saved inside the string than it can save, limiting it to its maximum size.
The problem is that the width modifier is a literal inside the scanf format string and I don't know how to indicate a value using a variable or constant. In printf there is the * modifier that allows you to indicate, as one more argument, the value of said width. For example:
#define ANCHO 10
printf("%*s", ANCHO, cadena);
This prints a string of maximum 10 characters (or whatever value is passed in place of 10). But in scanf, the * modifier does not have the same function, but rather it is used to ignore the reading of certain types of data. For example:
int entero = 0;
scanf("%*s %d", &entero);
Here, typing in a string and an integer would ignore the string and the integer would be stored in the integer variable.
I would like to know how the width value can be specified in the scanf modifier from a variable, without having to directly specify the value as a literal within the format string when calling scanf.
I've seen that you could use the sprintf function to prefetch the formatted string to use later in scanf. For example:
In this way, the maximum number of characters read by the keyboard would be limited to the WIDTH value. I would like to know if there is any other way that I can do all this without having to use the sprintf function before scanf.
Responding to the answer: