1

For example, here is a C common #define:

#define USERNAME_LEN  100
#define SCAN_FMT  "%100s"

// str is input from somewhere
char username[USERNAME_LEN + 1];
ret = sscanf(str, SCAN_FMT, username);
// check ret == 1 ? 

can we have something like:

#define SCAN_FMT   "%" USERNAME_LEN "s"

of course, this syntax is not what we want, but the ultimate goal is to mix numeric #define into string #define

Note: I know we can do something like:

sprintf(SCAN_FMT, "%%ds", USERNAME_LEN); // char SCAN_FMT[10];

but this is not what I am looking for, because it requires run-time generation, the best is to base on ANSI-C or std99.

1

2 Answers 2

2

You might like to do it like this:

#define SCAN_FMT_STRINGIFY(max) "%"#max"s"
#define SCAN_FMT(max) SCAN_FMT_STRINGIFY(max)

#define USERNAME_MAXLEN (100)

...

  char username[USERNAME_MAXLEN + 1] = ""; /* Add one for the `0`-terminator. */
  int ret = sscanf(str, SCAN_FMT(USERNAME_MAXLEN), username);
Sign up to request clarification or add additional context in comments.

Comments

2

You can use the preprocessor directives for these kind of tasks.

1.The first directive is # allows you to do such things:

#define str(x) #x
cout << str(test);

This will be translated into:

cout << "test";

2.The second directive is ##:

#define glue(a,b) a ## b
glue(c,out) << "test";

will be translated into:

cout << "test";

Look here for more info preprocessor

2 Comments

There is a piece missing. OP wants to stringize a defined value after it has been substuted. IIRC, doing so requires a third #define.
Not that it matters much for your answer, but the question is tagged C and no C++.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.