Pregunta

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.

¿Fue útil?

Solución

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

Otros consejos

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

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

Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top