user1690220
user1690220

Reputation: 3

Macro String with variable

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?

Upvotes: 0

Views: 445

Answers (2)

Daniel Fischer
Daniel Fischer

Reputation: 183873

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

using the stringification operator #

Upvotes: 1

Kerrek SB
Kerrek SB

Reputation: 476930

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.

Upvotes: 5

Related Questions