no**********@gmail.com wrote:
Hi,
I have a project that's supposed to create a program for a "Dating
Service". The first part of the program is to read a textfile of
profiles which include names, age, etc...into a string array, and be
able to add,edit,remove to the textfile of profiles during runtime.
What would be the most efficient way to do this to make it easiest as
possible to make changes to the textfile during time and access
elements of the array?
john
First, don't use an array or a raw buffer; use a std::vector of
std::strings (see
http://www.parashift.com/c++-faq-lit...html#faq-34.1). If you
do this, use the getline function, something like this:
ifstream file( "dating.txt" );
vector<string> v;
string line;
while( getline( file, line ) )
{
v.push_back( line );
}
// Now process the vector of strings
Alternately, you might consider implementing an extraction operator for
your data structure. Something like:
struct Person
{
string first, last;
unsigned int age;
// ...
};
istream& operator>>( istream& is, Person& p )
{
is >> p.first >> p.last >> p.age;
return is;
}
Then you could use it like this:
vector<Person> v;
Person p;
while( file >> p )
{
v.push_back( p );
}
// Now process the vector of People
Note that you can't generally modify data in the middle of a file (e.g.
by seeking to a certain point and trying to overwrite the data), so you
may need to write the entire data file each time.
Cheers! --M