4

Usually, I use a define for the size of a string, but when I use scanf(), I want to guard the function from reading too many characters (and reserve space for the null-terminator). I was wondering whether I could do this using my define, instead of a hardcoded magic number...

#include <stdio.h>

#define MAXLEN 4

int main(void) {
    char a[MAXLEN];
    scanf("%3s", a); // Can I do that with 'MAXLEN' somehow?
}

Is it possible? If yes, how?

gsamaras
  • 71,951
  • 46
  • 188
  • 305

1 Answers1

9

Use defines to stringify:

#define LENSTR_(x) #x
#define LENSTR(x) LENSTR_(x)

then you can use:

#define MAXLEN 3

char a[MAXLEN + 1];
scanf("%" LENSTR(MAXLEN) "s", a);
gsamaras
  • 71,951
  • 46
  • 188
  • 305
xing
  • 2,125
  • 2
  • 14
  • 10