3

this is the first time i am using getline() and i think there is something wrong with it! Here is my code:

ifstream file ("new2.csv");
string val;
while (file.good())
{
    getline (file,val);
}
cout<<val;

and the output is always the last line of the csv file, no matter how many lines i have in the csv file.

my csv file is a simple Delimited file. like:

cat,dog,a,b,c,hello,world
monkey,flower,text,word

i think getline is supposed to read the first line of the csv file, but in this case, my output will be : monkey,flower,text,word

and this happens with any number of lines in the csv file. i am unable to find out what may be doing this. please help me. thanks.

  • You've got a loop there... what makes you think it'll read the first line and then stop looping? – jrok Dec 25 '12 at 12:20
  • Well, you loop through, grab each line into the same variable, overwriting what it had previously, and then output it. What do you expect? – chris Dec 25 '12 at 12:20
  • I'd probably go with `while (std::getline(file, val)) {std::cout << val;}` and forget about the whole `good()` part. – chris Dec 25 '12 at 12:23

2 Answers2

2

Ofcourse it will only print the last line read from the file, because cout prints outside the loop and it prints the last line, after reading ALL lines finished.

You should write this instead:

ifstream file ("new2.csv");
string val;
while (file.good())
{
    getline (file,val);
    cout<< val << endl;
}
StackHeapCollision
  • 1,743
  • 2
  • 12
  • 19
1
while (file.good())
{
    getline (file,val);
}
cout<<val;

Your cout is outside the loop, so you'll only print the last line.

JasonD
  • 16,464
  • 2
  • 29
  • 44