简体   繁体   中英

getline can't get the first line of the file

Hi I am new here and i need help for my assignment. I want to read data from a file. I've used getline but it wont read the first line inside the file, can someone help me please? Here is my code:

void test(std::ifstream& infile, string& a, string& b, string& c) 
{
   infile >> a;
   infile >> b;
   infile >> c; 
}

int main() 
{
   ifstream file_("Level1.txt");
   string line;
   string a, b, c;

   while (getline(file_, line))
   {
       test(file_, a, b, c);
   }

   cout << a << " " << b << " " << c;
   return 0;
}

in my file:

aa
bb
cc

but output:

bb cc

Getline is getting the current line, so your strings look like this

a = "bb"
b = "cc"
c = ""

since you have already read the fist line and it is stored in line .You can just check if the file is open and then call your test function since it will start at the beginning of the file without skipping the first line.

if(file_.is_open())
{
    test(file_, a, b, c);
}

If the stream supports peek interface (which it generally does support), you might want to check your loop condition to be like this:

while (file_.peek() != EOF)

This will do the trick (and will do exactly as I thought eof() would behave).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM