在C ++中将变量名转换为字符串

时间:2022-02-26 16:38:37

I'd like to output some data to a file. For example assume I have two vectors of doubles:

我想将一些数据输出到文件中。例如,假设我有两个双精度向量:

vector<double> data1(10);
vector<double> data2(10); 

is there an easy way to output this to a file so that the first row contains the headings 'data1' and 'data2' followed by the actual contents. The function which outputs the data will be passed various different arrays so hardcoding the name of the heading is not possible - ideally I'd like to convert the variable name to some string and then output that string followed by the contents of the vector array. However, I'm not sure how to convert the variable name 'data1' to a string, or indeed if it can easily be done (from reading the forums my guess is it can't) If this is not possible an alternative might be to use an associative container such as map or perhaps more simply a 'pair' container.

是否有一种简单的方法将其输出到文件,以便第一行包含标题'data1'和'data2',后跟实际内容。输出数据的函数将传递各种不同的数组,因此不可能硬编码标题的名称 - 理想情况下,我想将变量名转换为某个字符串,然后输出该字符串,后跟向量数组的内容。但是,我不确定如何将变量名'data1'转换为字符串,或者确实如果它可以很容易地完成(从阅读论坛我的猜测是不可能)如果这是不可能的替代可能是使用关联容器(如map)或更简单的“对”容器。

pair<vector<double>,string> data1(10,'data1');  

Any suggestions would be welcome!

欢迎大家提出意见!

8 个解决方案

#1


34  

You can use the preprocessor "stringify" # to do what you want:

您可以使用预处理器“stringify”#来执行您想要的操作:

#include <stdio.h>

#define PRINTER(name) printer(#name, (name))

void printer(char *name, int value) {
    printf("name: %s\tvalue: %d\n", name, value);
}

int main (int argc, char* argv[]) {
    int foo = 0;
    int bar = 1;

    PRINTER(foo);
    PRINTER(bar);

    return 0;
}


name: foo   value: 0
name: bar   value: 1

(Sorry for printf, I never got the hang of <iostream>. But this should be enough.)

(对不起printf,我从未得到过 。但这应该足够了。)

#2


4  

try this:

#define GET_VARIABLE_NAME(Variable) (#Variable)

//in functions

int var=0;    
char* var_name= GET_VARIABLE_NAME(var);

#3


2  

You can use the preprocessor, there's a stringify token, but it's only available from the source, not to a function (you'd get the argument name).

您可以使用预处理器,这是一个stringify令牌,但它只能从源代码获得,而不是函数(您可以获得参数名称)。

#4


1  

I'd have thought the obvious answer is to make the function that performs the output take the heading text as a string parameter.

我认为显而易见的答案是使执行输出的函数将标题文本作为字符串参数。

#5


1  

Slightly adapted from @sarnold's answer, for C++:

对于C ++来说,略微改编自@ sarnold的答案:

#define DEBUG(x) std::cout << #x << " = " << x << std::endl;

An example program which uses this:

一个使用它的示例程序:

int main() {
    int foo = 1;
    DEBUG(foo);

    return 0;
}

#6


0  

I had the same problem. After a little bit of experimentation I created following macros that convert names of variables, fields, functions, methods and types to strings.

我有同样的问题。经过一些实验,我创建了以下宏,将变量,字段,函数,方法和类型的名称转换为字符串。

#define MACRO_VARIABLE_TO_STRING(Variable) (void(Variable),#Variable)

#define MACRO_FUNCTION_TO_STRING(Function) (void(&Function),#Function)

#define MACRO_METHOD_TO_STRING(ClassName,Method) (void(&ClassName::Method),#Method)

#define MACRO_TYPE_TO_STRING(Type) (void(sizeof(Type)),#Type)

The code uses comma operator and void conversion to force compiler to check if variable, function, etc. really exists. The nice thing is that it works well with uninitialized variables too. I tested it on both VC and GCC with all pedantic options I found out without any warning messages.

代码使用逗号运算符和void转换来强制编译器检查变量,函数等是否确实存在。好的一点是,它也适用于未初始化的变量。我在VC和GCC上测试了它,我发现了所有迂腐的选项而没有任何警告信息。

int GetAndPrintValue(const char* VariableName)
{
   std::cout << VariableName << std::endl;
   return 10;
}

int Variable=GetAndPrintValue(MACRO_VARIABLE_TO_STRING(Variable));

I use such code when I write parsers that reads data from input stream and if parsed variable is out of bounds it throws an exception with name of variable that failed my validity checks.

我在编写从输入流中读取数据的解析器时使用此类代码,如果解析变量超出范围,则会抛出一个异常,其变量名称无法通过有效性检查。

#7


0  

For this case I have made nameof() macro. It returns a std::string name of a variable, type or member. It works like nameof() in C#.

对于这种情况,我已经创建了nameof()宏。它返回变量,类型或成员的std :: string名称。它的作用类似于C#中的nameof()。

For Example:

#include "nameof.h"

std::vector<double> data1(10);
std::string name = nameof(data1); // "data1"

struct Foo1
{
    struct Foo2
    {
        Foo1* foo1;
    };

    Foo1* foo1;
    Foo2 foo2;
};

name = nameof(Foo1::foo1->foo2.foo1); // "foo1"

name = nameof(123); // std::logic_error exception

#8


-3  

Wow, this is a bit trickey, one thing you could try to do is make classes or structs, which have an element that is the string 'name'.

哇,这有点三角,你可以尝试做的一件事就是制作类或结构,它有一个字符串'name'。

#1


34  

You can use the preprocessor "stringify" # to do what you want:

您可以使用预处理器“stringify”#来执行您想要的操作:

#include <stdio.h>

#define PRINTER(name) printer(#name, (name))

void printer(char *name, int value) {
    printf("name: %s\tvalue: %d\n", name, value);
}

int main (int argc, char* argv[]) {
    int foo = 0;
    int bar = 1;

    PRINTER(foo);
    PRINTER(bar);

    return 0;
}


name: foo   value: 0
name: bar   value: 1

(Sorry for printf, I never got the hang of <iostream>. But this should be enough.)

(对不起printf,我从未得到过 。但这应该足够了。)

#2


4  

try this:

#define GET_VARIABLE_NAME(Variable) (#Variable)

//in functions

int var=0;    
char* var_name= GET_VARIABLE_NAME(var);

#3


2  

You can use the preprocessor, there's a stringify token, but it's only available from the source, not to a function (you'd get the argument name).

您可以使用预处理器,这是一个stringify令牌,但它只能从源代码获得,而不是函数(您可以获得参数名称)。

#4


1  

I'd have thought the obvious answer is to make the function that performs the output take the heading text as a string parameter.

我认为显而易见的答案是使执行输出的函数将标题文本作为字符串参数。

#5


1  

Slightly adapted from @sarnold's answer, for C++:

对于C ++来说,略微改编自@ sarnold的答案:

#define DEBUG(x) std::cout << #x << " = " << x << std::endl;

An example program which uses this:

一个使用它的示例程序:

int main() {
    int foo = 1;
    DEBUG(foo);

    return 0;
}

#6


0  

I had the same problem. After a little bit of experimentation I created following macros that convert names of variables, fields, functions, methods and types to strings.

我有同样的问题。经过一些实验,我创建了以下宏,将变量,字段,函数,方法和类型的名称转换为字符串。

#define MACRO_VARIABLE_TO_STRING(Variable) (void(Variable),#Variable)

#define MACRO_FUNCTION_TO_STRING(Function) (void(&Function),#Function)

#define MACRO_METHOD_TO_STRING(ClassName,Method) (void(&ClassName::Method),#Method)

#define MACRO_TYPE_TO_STRING(Type) (void(sizeof(Type)),#Type)

The code uses comma operator and void conversion to force compiler to check if variable, function, etc. really exists. The nice thing is that it works well with uninitialized variables too. I tested it on both VC and GCC with all pedantic options I found out without any warning messages.

代码使用逗号运算符和void转换来强制编译器检查变量,函数等是否确实存在。好的一点是,它也适用于未初始化的变量。我在VC和GCC上测试了它,我发现了所有迂腐的选项而没有任何警告信息。

int GetAndPrintValue(const char* VariableName)
{
   std::cout << VariableName << std::endl;
   return 10;
}

int Variable=GetAndPrintValue(MACRO_VARIABLE_TO_STRING(Variable));

I use such code when I write parsers that reads data from input stream and if parsed variable is out of bounds it throws an exception with name of variable that failed my validity checks.

我在编写从输入流中读取数据的解析器时使用此类代码,如果解析变量超出范围,则会抛出一个异常,其变量名称无法通过有效性检查。

#7


0  

For this case I have made nameof() macro. It returns a std::string name of a variable, type or member. It works like nameof() in C#.

对于这种情况,我已经创建了nameof()宏。它返回变量,类型或成员的std :: string名称。它的作用类似于C#中的nameof()。

For Example:

#include "nameof.h"

std::vector<double> data1(10);
std::string name = nameof(data1); // "data1"

struct Foo1
{
    struct Foo2
    {
        Foo1* foo1;
    };

    Foo1* foo1;
    Foo2 foo2;
};

name = nameof(Foo1::foo1->foo2.foo1); // "foo1"

name = nameof(123); // std::logic_error exception

#8


-3  

Wow, this is a bit trickey, one thing you could try to do is make classes or structs, which have an element that is the string 'name'.

哇,这有点三角,你可以尝试做的一件事就是制作类或结构,它有一个字符串'name'。