Input the variable to output?

Hello, I was wondering if it where possible to input the name of a variable into a console and receive it's value, for example:
if int hello = 5;
and I type 'hello' into the console, I get '5' as a result.

if this is not possible, is it possible to output a location in memory which is specified by the user? of so, how would I do that?

Thank you for your help!
Last edited on
Essentially what your talking about is the way a debugging program works. As long as the program was compiled or assembled with this information you can extract it. All that needs be done is find out what the format of the file is where you're getting the information from. This is of course platform and compiler/assembler specific. Another way of doing it is;

1
2
3
4
5
6
7
  int hello;
  string variable;

  cin >> variable;

  if (variable == "hello" )
    cout << "The value @ hello is " << hello << endl;


There is a little more to this to make it work, but I think this will give you a general idea.
If you make a simple "variable" class, you will always be able to associate a variable with a number/word/anything and view them together. It is going a little out of the way, but it is probably a more complete solution.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
class Variable {
    private:
        string variableName;
        int value;
    public:
        Variable(string variableName, int value) {
            this->variableName = variableName;
            this->value = value;
        }

        int getValue() {
            return this->value;
        }
};

int getVariableValue(Variable v) {
    return v.getValue();
}

Variable x("hello", 5);
getVariableValue(x);


The above code would return the number 5. I believe this is what you were looking for. I'm not in a location where I can test this, but I believe it would work properly.
Thank you LimeOats, that's exactly what I need!
If you are going to have multiple variables, you will want to have some kind of associative container so that you dont' have to manually look up variables by name.

C++ has a built-in 'map' class which does just that:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
#include <map>
#include <string>

std::map<string,int> variables;

int main()
{
  variables["hello"] = 5;
  variables["world"] = 10;

  // to print the contents of a variable
  cout << variables["hello"];

  // to see if a variable has already been defined or not
  auto i = variables.find( "notdefinedyet" );
  if( i == variables.end() )
    cout << "Sorry, that variable has not been defined yet";
  else
    cout << "That variable has been defined.  Its value is " << *i;
}
Last edited on
Topic archived. No new replies allowed.