String as Variable Name

Jun 9, 2010 at 1:57pm
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.
Jun 9, 2010 at 2:04pm
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.
Jun 9, 2010 at 2:05pm
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 Jun 9, 2010 at 2:06pm
Jun 9, 2010 at 2:07pm
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;
}
Jun 9, 2010 at 2:17pm
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 Jun 9, 2010 at 2:18pm
Jun 9, 2010 at 3:05pm
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?
Jun 9, 2010 at 3:11pm
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.
Jun 9, 2010 at 3:14pm
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
Jun 9, 2010 at 3:15pm
I really don't know that "map" thing.
Jun 9, 2010 at 3:30pm
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
Jun 9, 2010 at 9:16pm
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...
Jun 9, 2010 at 10:55pm
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.