Question

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.

Was it helpful?

Solution

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;
}

OTHER TIPS

while (file.good())
{
    getline (file,val);
}
cout<<val;

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

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top