Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

scanf() variable length specifier

Tags:

c

scanf

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.

like image 406
CS Student Avatar asked Aug 20 '14 17:08

CS Student


People also ask

Which format specifier we used in scanf () to scan a string?

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.

How do I format scanf?

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.


3 Answers

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"

like image 98
R Sahu Avatar answered Sep 22 '22 11:09

R Sahu


#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;
}
like image 38
BLUEPIXY Avatar answered Sep 22 '22 11:09

BLUEPIXY


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);
}
like image 30
Daniel Trugman Avatar answered Sep 19 '22 11:09

Daniel Trugman