Scanf () variable length specifier

How can I use a variable to indicate the maximum number of characters scanf() should read?

For example, using printf() , you can use * so that

 #define MAXVAL 5 printf("Print at maximum MAXVAL chars: %.*s\n", MAXVAL, "myStringHere"); 

This will print only 5 characters, how can I do scanf read-only in MAXVAL? MAXVAL should be used as a length specifier. I can't just

 scanf("%5s", string); 

For now, I can only think of reading in a large array using scanf , then using ssprintf to save the string in my limited length length. Using a length specifier would be much simpler.

+8
c scanf
source share
4 answers

You can use the C preprocessor to help you with this.

 #define STR2(x) #x #define STR(X) STR2(X) scanf("%" STR(MAXVAL) "s", string); 

The processor combines the "%" STR(MAXVAL) "s" and "%5s"

+13
source share
 #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; } 
+5
source share

You can not. You need to use something other than scanf() . A good and popular choice is fgets() , although its semantics are slightly different: fgets() will read the input line, while scanf() with %s will read whitespace separator sequences of characters.

To use fgets() , you need something like:

 fgets(string, MAXVAL, stdin); 

If for some reason you really want to use scanf() , take a look at this question: How to prevent a scan causing a buffer overflow in C?

+2
source share

Kernigan and Pike recommend using snprintf () to create a format string. I developed this idea in a method that reads strings safely:

 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); } 
0
source share

All Articles