String as Variable Name

I'm trying to use a string as a variable name but I don't know how.
For example, str declared as a string and gets the value of "number" and I wanted to use the value of the str to be the variable name of an integer type.
You can't. Variable names don't work that way.
The effect can be emulated, but first I'd like to know why you think you need to do this.
C and C++ don't work that way.

Unless you are writing an interpreter of some sort, you need to rethink how you want to do this.

What exactly are you trying to accomplish?

Too slow...
Last edited on
That's not possible in this exact way. Variables no longer have names once the program is compiled.
What you can do is to use a map:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
#include <iostream>
#include <map>
#include <string>
using namespace std;

int main()
{
    map<string,int> variableMap;
    variableMap["variable"]=10;
    variableMap["anotherVariable"]=0;
    variableMap["test"]=556;
    variableMap["x"]=42;
 
    cout << "Enter a variable name: " << flush;
    string varName;
    cin >> varName;
    cout << varName << "\'s value is: " << variableMap[varName] << endl;
}
Just to through around some useful terminology, a map is an associative container. I'm assuming that the OP has the intention of associating a string with a variable.
Last edited on
I'm doing a simple C++ interpreter and I'm having problems if the cpp file declared a variable and used it in the succeeding lines. Any way around to resolve this?
interpreter
In that case, yes. You need an associative container of some sort. See Athar's post for an example.

PS: You chose a really bad language to interpret.
Either an associative container from the STL or an object you made yourself could work. I personally recommend one you make yourself for interpreting a language like C++.

-Albatross
I really don't know that "map" thing.
If only there were some online resource to find information about C++ STL containers.

http://www.google.com/search?q=stl+map+reference

Ironically, the first result points to a page on this domain.

--Rollie
A C++ compiler/interpreter is one of the most complex language programs you can choose to write. I suggest you work with a very small subset of the language...
The generic structure of the C language is good to start with (implement control structures, functions, structs, some preprocessor directives, but nothing significantly more advanced). Once you do that, start implementing exception handling, then slowly objects, then templates, and so on.

-Albatross
Topic archived. No new replies allowed.