Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

converting a variable name to a string in C++

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.

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

Any suggestions would be welcome!

like image 473
Wawel100 Avatar asked Aug 02 '10 10:08

Wawel100


People also ask

How do you convert a variable to a string?

Converting Numbers to Strings We can convert numbers to strings through using the str() method. We'll pass either a number or a variable into the parentheses of the method and then that numeric value will be converted into a string value.

Can string be a variable name?

A string variable is a variable that holds a character string. It is a section of memory that has been given a name by the programmer. The name looks like those variable names you have seen so far, except that the name of a string variable ends with a dollar sign, $. The $ is part of the name.

What is #variable in C?

Variable is basically nothing but the name of a memory location that we use for storing data. We can change the value of a variable in C or any other language, and we can also reuse it multiple times.

Which line of code would you use to print the value of a variable named result to the screen?

Code - f-string.


2 Answers

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

#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.)

like image 141
sarnold Avatar answered Sep 20 '22 01:09

sarnold


try this:

#define GET_VARIABLE_NAME(Variable) (#Variable) 

//in functions

int var=0;     char* var_name= GET_VARIABLE_NAME(var); 
like image 43
SaeidMo7 Avatar answered Sep 21 '22 01:09

SaeidMo7