scanf: template with macro (#define constant) insi

2019-07-21 18:28发布

问题:

I have a bit of code like here:

#define MAXSIZE 100

int main() {
    char str[MAXSIZE+1];
    scanf("%100s", str);
    ...

The problem is I still have "magic number" 100, although defined MAXSIZE. Is there a way to properly "insert" MAXSIZE into scanf format string? (pure C, c-99 standart)

回答1:

There is, but you'd be better off using fgets():

if (fgets(str, sizeof str, stdin) != NULL) {
    // process input
}

The good thing about this (apart from an undoubted readability boost) is that fgets() takes care of the size correctly, i. e. it accounts for the terminating 0 character (which scanf() doesn't), so you don't have to hack around with adding one to the size when declaring your buffer. It also always NUL-terminates the array for you. Way less error prone.


As to the original question: try the usual "stringify" trick:

#define REAL_STRINGIFY(x) #x
#define STRINGIFY(x) REAL_STRINGIFY(x)

scanf("%" STRINGIFY(MAXSIZE) "s", str);

But this is very ugly, isn't it?



标签: c scanf