converting a variable name to a string in C++

前端 未结 8 1030
广开言路
广开言路 2020-12-01 01:15

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

vector data1(10);
vector data2(10); 
         


        
8条回答
  •  不知归路
    2020-12-01 02:01

    I had a similar quest. In Qt, I got tired of constantly writing the variable name as a string without autocomplete when writing to qDebug(). After a lot of trial and error with different macros and functions, I found that this macro works great:

    #define PRINT(x) ", " << #x << ": " << x
    

    Example usage:

    int someVariable = 42;
    double anotherVariable = 13.37;
    qDebug().nospace() << "Some text" << PRINT(someVariable) << PRINT(anotherVariable);
    

    Output:

    Some text, someVariable: 42, anotherVariable: 13.37
    

    I guess this (or something very similar) will work for std::cout as well.

    A bit late to the party, but I hope this can help anyone out there!

提交回复
热议问题