writing an objects name to file

Started by
9 comments, last by alvaro 12 years, 9 months ago
i have a class, for the purpose of this question it is a simple class called person which stores their age and height (in cm). Now say i wanted to write the objects of this class to a file, the name of the object would be the persons name, and the class contents would obviously be the relevant persons age and height. How would i go about writing all this information to a file (including the persons name), for recall without defining the persons name as a string within the class?


#include <iostream>
#include <fstream>

using namespace std;

class person
{
public:
int age;
int height;
}

int main() {
person bob;
ofstream myfile;
myfile.open("file.txt", ios::app);
bob.age = 18;
bob.height = 180;
myfile << /*write the object name somehow*/"" << bob.age << " " << bob.height << "\n";
myfile.close();
return 0;
}


i hope my question has made sense.

Thanks in advance
Advertisement
You can't. Objects don't have names in C++. In your code, you can use "bob" as a string constant, but I doubt that's what you wanted.
so there is no way to be able to write to a file: bob 18 180?

i guess this would then apply to any variable, so while it is possible to write the variable value to a file, you cannot write the variable name?
I don't know what part of my answer wasn't clear.
You can write the name as a string literal.
myfile << "bob " << bob.age << " " << bob.height << "\n";

If person has a name in your program you should just store it as a member of person
no, it was clear, i guess i was just hoping for a different answer, but obviously one does not exist. thank you for your help.
You can using a macro like:


#define NAME_OF(x) #x
....
myfile << NAME_OF(bob) << bob.age;


with this macro you can get the string of any expression.
Just give the person a class a "string name" field? I would think that would be the proper way to handle it.


class person
{
public:
string name;
int age;
int height;
}

int main()
{
person bob;
ofstream myfile;
myfile.open("file.txt", ios::app);
bob.name = "Bob";
bob.age = 18;
bob.height = 180;
myfile << bob.name << bob.age << " " << bob.height << "\n";
myfile.close();
return 0;
}
What RedEyedKiller says works but it is just overcomplicated to be useful. It is so much easier to write "bob" than write NAME_OF(bob) when both do the exact same thing.
This is what I do in my Logging system (I hope it's useful :) )


//the macro
#define ECHO_EXPR(x) #x " = " << x << " "

//overload << operator to make logging easier
std::ostream& operator << (std::ostream& stream,const ClassA& arg)
{
stream << arg.GetMemberA() << " " << arg.GetMemberB();
return stream;
}

//the actuall use
file << ECHO_EXPR(var1);


edit:sorry for the typo

This topic is closed to new replies.

Advertisement