I wanted to know if there is such a way to declare a variable at runtime or create a dynamic variable. I've done this in Python, but I didn't know if C++ allows this. Maybe I'm not explaining it that well so I will give an example. Say I have an input file that lists the name of a variable and a associated integer:

a 3
b 897
c 645
...

So I would like to have a=3...How can this be done in C++?

You can't read the letter a from a file, and then assign a variable with the name a really dynamically.

I guess if the variable names that you read from the file are only a,b,c etc. you could put them in an array, using the integral value of 'a' as an index, it's not very elegant though.

You can also create a map<string,int> which maps the 'a' to it's integral value that you read from the file... I guess that would be a lot better.

You can't do that directly in C or C++. What I would do is create a structure that contains the variable name and value

struct item
{
   std::string name;
   int value;
};

Then you can have a vector of those variables vector<item> data; Another way to do it is to use std::map to map the variable name and integer value.

#include <string>
#include <map>
using std::string;
using std::map;

int main()
{
    std::map <string, int> data;
    data["a"] = 1;
    data["b"] = 2;
    data["c"] = 3;
}
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.