read every other string from a text file

A

aarthi28

Hi,
I am trying to read every other string from a text file and store it
in a vector. I can use istream_iterator to read all strings and store
it in a vector. However, I only need the first, third,5th etc string
in a vector. How do I do this?
Thanks a lot. Any help I can get is appreciated
 
V

Victor Bazarov

I am trying to read every other string from a text file and store it
in a vector. I can use istream_iterator to read all strings and store
it in a vector. However, I only need the first, third,5th etc string
in a vector. How do I do this?

In a loop, maybe? Like, while the stream is good, read the line, store
it, then read one more, throw it out, repeat...

V
 
A

aarthi28

Here is the part of the code that I'm not sure how to modify. This
reads every word and stores it in the buffer. I need to store only
every alternate word and I don't know how to do that

void read_file(const string file_name, vector<string>& buffer)
{
ifstream in_file(file_name.c_str());
if (!in_file)
{
return;
}

istream_iterator< string > is(in_file);
istream_iterator< string > eof;
copy( is, eof, back_inserter(buffer));
}
 
V

Victor Bazarov

Here is the part of the code that I'm not sure how to modify. This
reads every word and stores it in the buffer. I need to store only
every alternate word and I don't know how to do that

void read_file(const string file_name, vector<string>& buffer)
{
ifstream in_file(file_name.c_str());
if (!in_file)
{
return;
}

istream_iterator< string > is(in_file);
istream_iterator< string > eof;
copy( is, eof, back_inserter(buffer));

Right here 'buffer' contains every word. What if you just remove
every other word from it here? You could use another vector, copy
only the evenly-indexed elements from 'buffer' to it (in a loop),
and then swap them (to return the correct one).

V
 
A

aarthi28

Thank you! I wasn't quite sure how I would do it, but I figured it out
with your help.
 

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
474,294
Messages
2,571,511
Members
48,198
Latest member
couriermedicine

Latest Threads

Top