How to use a input string to name a variable?

Aug 14, 2014 at 2:30pm
What I want to do is I want to input a string as:

string var_name;

cin >> var_name;

Then I need to use this string "var_name" as the variable name to create a new variable. E.g. : I input "length". I need an int variable:

int length;

How can I achieve it?


Thanks in advance.


Aug 14, 2014 at 2:47pm
Aug 14, 2014 at 2:47pm
Nope. You can't do that.
Aug 14, 2014 at 2:47pm
If all your "variables" have the same type (e.g. they are all ints) then you could use a map.

http://www.cplusplus.com/reference/map/map/
Aug 14, 2014 at 5:00pm
1. You can't. Variable names go away in compiled code. They are just useful for the programmer to give names to things in the source code. The computer doesn't need names to execute code.

2. Keep a mapping of names and values for the user.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
#include <iostream>
#include <map>
#include <string>
using namespace std;

int main()
{
  map <string, string> environment;
  
  cout << "Enter a list of variables as 'name=value'.\n"
          "Press ENTER when asked for a name to quit.\n";
  while (true)
  {
    cout << "name> ";
    string name;
    getline( cin, name );
    if (name.empty()) break;
    
    cout << "= ";
    string value;
    getline( cin, value );
    
    environment[ name ] = value;
  }
  
  cout << "\nGreat! Your names and values are:\n";
  for (auto e : environment)
  {
    cout << e.first << " = " << e.second << "\n";
  }
}

Hope this helps.
Topic archived. No new replies allowed.