reading file into string array

N

novacreatura

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
 
M

mlimber

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-lite/containers.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
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,756
Messages
2,569,534
Members
45,007
Latest member
OrderFitnessKetoCapsules

Latest Threads

Top