0

for example lets say your pulling data from somewhere and you put it in a string variable then you want to use the data inside of it to be the another strings name:

int main(void){

   string strVar ="StringData"; //this is a string variable with text inside 

   cout<<strVar<<endl;    //displaying the variables contents


   string strVar.c_str() = "stuff in string variable 'StringData'"; //this uses what was inside of strVar to be the name of the new string variable

   cout<<StringData<<endl; //prints the contents of the variable StringData (who got its name from the data inside of strVar
}

//OUTPUT:
StringData
stuff in string variable 'StringData'

i know you definitely cannot do it in this manner and in this example your would have to know before hand what was in strVar before you used the variable StringData, but can we theoretically do this?

Edit:

Thanks everyone, so what i get from you all is basically its not possible, C++ is not a Dynamic variable language and the closest thing i can get to it is with a map (string, string)

2
  • 1
    Probably map<string, string> is what you want? Commented Jun 25, 2012 at 4:12
  • The short answer: no, it's not possible. Commented Jun 25, 2012 at 4:15

4 Answers 4

2

Nothing explicitly like you are thinking, but maybe you'd be interested in a std::map? Sounds like what you want is a Key-Value pairing.

Reference for std::Map -> http://www.cplusplus.com/reference/stl/map/

Example:

#include <map>
#include <string>
#include <iostream>
using namespace std;

int main(void)
{
    map<string, string> myMap;
    myMap.insert(pair<string, string>("StringData", "Stuff in StringData"));

    // Get our data
    cout << myMap["StringData"] << endl;

    return 0;
}
Sign up to request clarification or add additional context in comments.

Comments

0

Variable names exist only at compile time in C++. The closest you can come is to use a map with string keys.

1 Comment

well then, ill have to seriously rethink my approach to this program then, thanks for the help @Antimony
0

I'm not sure what you're asking, but if you want to have "dynamic" variable names, then you can't do that in the code directly. You would have to use some map-type data construct. Look at std::hash_set or std::map if you can use the standard library.

Comments

0

There are languages where you can create variables dynamically. C++ isn't one of them ;)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.