2cs
2cs

Reputation: 33

How to getline() twice on same line in C++?

I have a file and I want to store the first part of a line until a ',' is reached, then store the remaining end of the line into another variable. Currently, it skips half the lines. For example this is three lines of my file:

021200725340,Scotch Removable Clear Mounting Squares - 35 Ct
041520035646,Careone Family Comb Set - 8 Ct
204040000000,Plums Black

My code only stores half of the lines:

while(getline(file, upc)){ 
    getline(file, upc, ',');        
    getline(file, description); 
}

Upvotes: 1

Views: 305

Answers (1)

R Sahu
R Sahu

Reputation: 206607

My code only stores half of the lines:

The call to getline inside the conditional of the while statement is responsible for that.

Change your code to:

while( getline(file, upc, ',') && getline(file, description) )
{
   // Use the data.
}

Upvotes: 5

Related Questions