如何在 C/C++ 中将宏替换文本变成字符串

how to make macro replacement text into a string in C / C++

我想知道是否可以创建一个包含预处理器宏替换文本的字符串文字。

E. G。一个定义了:

#define Number 2.847

程序应该将这个数字作为字符串输出。我试过了:

#define M(a) #a
int main() {
   cout << M(Number) << endl;
}

但是它输出的是“Number”而不是“2.847”。

有没有办法在不改变Number的定义的情况下让它工作?因为这个定义可能在标准 header 中,它甚至不作为文件存在。

你必须再做一遍。通常:

#include <iostream>   

#define NUMBER      2.847

#define STRING(a)   #a
#define XSTRING(a)  STRING(a)

int main() {
   std::cout << XSTRING(NUMBER) << '\n';
}