0

I don't know how to define a macro string with variable, like this:
#define str(x) "file x.txt", that mean I desire that str(1) refers to "file 1.txt". However, in the case, str(1) or any number refers to "file x.txt", because x is an character.
Is there any way to solve this?

1
  • The "with variable" might be tricky. If you have int foo=5; STR(foo) you're still talking about file foo.txt, not file 5.txt. Macro's work at compile time, before variables have values assigned. Commented Sep 25, 2012 at 8:28

2 Answers 2

5

Concatenate the strings:

#define STR(x) "file " #x ".txt"

This makes use of a lexical feature of the two languages: adjacent string literals are concatenated; see both C++11 2.2/6 and C11 5.1.1.2/6:

Adjacent string literal tokens are concatenated.

Sign up to request clarification or add additional context in comments.

Comments

1
#define str(x) ("file " #x ".txt")

using the stringification operator #

Comments

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.