Rabbit
Rabbit

Reputation: 3

c++ ifstream Skipping Data

I'm trying to get my program to read two lines out of a six line data file (the other four are two sets of two that are meant to be read to other objects). However, I can only get it to read one -- either the first or the second depending on how I manipulate the code.

Here's what's in my data file:

Mustang Sally
123.45
George Porge
11.99
J. D. Rockerfeller
56321.3

And here's the section of the code where I need to read said data:

void account::readAccount(ifstream &inFile)
{
    while (getline(inFile, name))
    {
        inFile.ignore();
        inFile >> savings;

    }


}

The code above is only reading in the second line.

I think I'm having a phantom newline problem, which I can't seem to resolve, but I also feel that there's another problem on top of that, which I can't comprehend with my current level of experience regarding file streams.

Upvotes: 0

Views: 521

Answers (1)

user3813674
user3813674

Reputation: 2683

The code above is only reading in the second line.

Yes because you tell it to ignore. I don't know what exactly two lines you want to get from these, but based on the codes, I'm assuming that you want to read the values at line 2,4. The following code will print out those two lines.

float savings = 0.0f;
while(getline(inFile,line))
{
  if(savings > 0.0f) cout << savings << endl;
  inFile >> savings;
  inFile.ignore(1000, '\n' );
}

Upvotes: 2

Related Questions