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
#define MAXVAL 5
printf("Print at maximum MAXVAL chars: %.*s\n", MAXVAL, "myStringHere");
This will only print 5 chars, how can I make scanf
only read in MAXVAL? MAXVAL must be used as the length specifier. I cannot simply do
scanf("%5s", string);
Right now I can only think of reading into a large array using scanf
then using ssprintf
to store the string into my length limited string. Using a length specifier would be so much easier however.
Here, we have used %d format specifier inside the scanf() function to take int input from the user. When the user enters an integer, it is stored in the testInteger variable.
Format Conversions: scanf, fscanf, sscanf. To get started, use %hi to input a short, %i for an int, %li for a long, %f for a float, %lf for a double, %Lf for a long double, %c for a char (or %i to input it as a number) or %s for a string (char * or char []). Then refine the formatting further as desired.
You can use the C preprocessor to help you with that.
#define STR2(x) #x
#define STR(X) STR2(X)
scanf("%" STR(MAXVAL) "s", string);
The processor combines "%" STR(MAXVAL) "s"
to "%5s"
#include <stdio.h>
#define MAXLEN 5
#define S_(x) #x
#define S(x) S_(x)
int main(void){
char string[MAXLEN+1];
scanf("%" S(MAXLEN) "s", string);
printf("<%.*s>\n", MAXLEN, string);
return 0;
}
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 %<num>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);
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With