getline() function in visual studio 2012 working differently, directly skipping to the last line

StackOverflow https://stackoverflow.com/questions/14030590

سؤال

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.

هل كانت مفيدة؟

المحلول

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

نصائح أخرى

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

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

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top