Alessandro Lorusso
Alessandro Lorusso

Reputation: 357

How do I loop through input line by line and also go through each of those lines in C++;

So I'm trying to go through input line by line. Each line in the input is formatted like this:

Words_More words_even more words_What I Need to Go Through_ Random_ Random_Etc.

With a random amount of word clusters (The words separated by '_')

I want, for each line, to be able to ignore all the words until I get to the fourth word cluster which in the example I gave would be: "What I Need To Go Through" and then store those separate words in some data structure that I haven't decided upon yet.

My first thought would be to use

    getline(cin, trash, '_'); 

three times and deal with the data that follows, but then how would I loop line by line until the end of the input?

Upvotes: 0

Views: 209

Answers (1)

David van rijn
David van rijn

Reputation: 2220

You basically have two options:

use getline for each line, then parse it

use getline(stream, string) to get a line from your stream, and store it into a string. Then construct an istringstream to parse this again (with the getline you thought of.

get what you need, and then ignore() stuff unill the next newline

You do getline() thing, and then you call ignore() (doc) to read and discard the rest of the line, so you can start again with the next line.

which one you use is up to you. but the second one has slightly better performance, if you care about that stuff.

Upvotes: 1

Related Questions