cscanf

scanf() variable length specifier


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.


Solution

  • 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"