You can't make variables at runtime without delving into really weird voodoo that operates outside the bounds of legal C++. It's not worth doing it. And even if you could, the variable names are early casualties while compiling. That variable file
isn't called file anymore. It's probably something like stackpointer + 32 by the time the compiler and linker are through with it. So the idea of dynamically loading a variable name at runtime just isn't going to work.
But you can make a variable that maps the name of a person to an instance of your structure. The C++ standard library contains a couple such mapping classes, for example, std::map
.
An example of using std::map
for your case could look like:
std::ifstream file;
std::map<std::string, newperson> people;
std::string name;
std::string hair_colour;
int age;
if (getline(file, name) &&
getline(file, haircolor) &&
file >> age)// note: I left a boobytrap here
{ // only add the person if we got a name, a hair colour and an age
people[name].hair_colour = hair_colour; // creates a newperson for name and sets
// the hair_colour
people[name].age= age; // looks up name, finds the newperson and sets their age.
// warning: This can be a little slow. Easy, but slow.
}
Hint on boobytrap: Why does std::getline() skip input after a formatted extraction?
Later when you want to look up Sandy's age,
people["Sandy"].age
is all you need. But watch out, if Sandy is NOT in the the people
map, the map will create and default-construct a new entry for Sandy. If you aren't certain Sandy is in the map, use the find
method instead.