C/C ++中的字符串化运算符 [英] Stringizing operator in C/C++

查看:178
本文介绍了C/C ++中的字符串化运算符的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用字符串化运算符#,但出现错误stray ‘#’ in program.这是我的使用方式.

I am trying to use the stringizing operator #, but I get the error stray ‘#’ in program. Here is how I am using it.

#define STR "SOME_STRING"
#define BM 8
#define NUM_OF_THREADS 8
#define VER_STR (STR #BM #NUM_THREADS)

我希望得到VER_STRSOME_STRING88,但会出现错误.我在做什么错?

I expect to get SOME_STRING88 for VER_STR but instead get an error. What mistake am I doing?

推荐答案

您需要将数字常量转换为字符串.但是,#BM是一个错误,因为该语法仅对宏参数有效. 因此,您需要通过中间宏强制进行扩展.您也可以使用STRINGIFY宏:

You need to turn the numerical constants into a string. However, #BM is an error, since the syntax is only valid for macro parameters. So you need to force en expansion through an intermediate macro. And you may as well have a STRINGIFY macro to do it:

#include <iostream>

#define STRINGIFY_(x) #x
#define STRINGIFY(x) STRINGIFY_(x)

#define STR "SOME_STRING"
#define BM 8
#define S_BM STRINGIFY(BM)
#define NUM_OF_THREADS 8
#define S_NUM_OF_THREADS STRINGIFY(NUM_OF_THREADS)
#define VER_STR STR S_BM S_NUM_OF_THREADS

int main() {
    // your code goes here
    std::cout << VER_STR;
    return 0;
}

您可以在 http://ideone.com/cR1KZP

编辑

正如Magnus Hoff所指出的,您也可以直接调用STRINGIFY:

As Magnus Hoff pointed out, you can invoke STRINGIFY directly as well:

#define VER_STR STR STRINGIFY(BM) STRINGIFY(NUM_OF_THREADS)

这篇关于C/C ++中的字符串化运算符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆