Hackermann
Hackermann

Reputation: 43

Reading from multiple lines from a txt file in a single iteration

I am working at the moment with linked lists, and my nodes have 4 elements( where each of them is a variable type string). In a .txt file there are groups of text where each group has 4 lines, for example:

and so on and so on... What I'm trying to achieve is reading the four lines in a single iteration and give them to a node, and let the program iterate until there is no more lines.

So if reading the example above our nodes will be left with;

Node1.string1 = This is the first line;

Node1.string2 = This is the second line;

Node1.string3 = This is the third line;

Node1.string4 = This is the fourth line;

While looking for a way to do this on internet, I found one way you can do this and tell the "ifstream reader" to do a '\n' before the next iteration, but I lost this page and cant seem to find it

Upvotes: 0

Views: 139

Answers (1)

john
john

Reputation: 87944

Easy enough

while (getline(in, node.string1) && 
    getline(in, node.string2) && 
    getline(in, node.string3) && 
    getline(in, node.string4))
{
    ...
    string dummy;
    getline(in, dummy); // skip blank line
}

You can also use in.ignore(std::numeric_limits<std::streamsize>, '\n'); to skip the blank line, but reading into a dummy variable allows you to easily check if the blank line really is blank.

Upvotes: 2

Related Questions