What’s actual mechanism happen when we try to extract line in file after which `eof“ character is present with istream::getline() and std::getline()

  c++, eof, file-handling, getline, string

roha.txt

I really love to spend time with you.
Let's go for coffee someday.
Enjoy whole day and cherish the memories.

Code-1

#include <iostream>
#include <fstream>


int main()
{
    char str[100];

    std::ifstream fin;
    fin.open("roha.txt", std::ios::in);

   for(int i=0; i<=3; i++)
   {
        std::cout<<bool(fin.getline(str,100) )<<" "<<str<<fin.fail()<<"n";
   }

}

Output

1 I really love to spend time with you.0
1 Let's go for coffee someday.0
1 Enjoy whole day and cherish the memories.0
0 1

Code-2

#include <iostream>
#include <fstream>
#include <string>
using std::string;

int main()
{
   string str;

    std::ifstream fin;
    fin.open("roha.txt", std::ios::in);

    for(int i=0; i<=3; i++)
    {
        std::cout<<bool(std::getline(fin,str) )<<" "<<str<<fin.fail()<<"n";
    }

}

Output

1 I really love to spend time with you.0
1 Let's go for coffee someday.0
1 Enjoy whole day and cherish the memories.0
0 Enjoy whole day and cherish the memories.1

I know C-style char array, istream::getline and string, std::getline are different. But I want to know what actually happens.

Like I am guessing that for string, std::getline Like it extracts string for 1st, 2nd and when it try to extract 3rd time it sees eof so it extract just before eof and then for next time we try to extract
it, just encounters eof so it didn’t extract anything and set fail-bit and as string str didn’t modified so as we try to print it last extracted string only print. I don’t know what I think is right or wrong ?

Also I am not able to make any such case regarding istream::getline(), C-style char array.

Source: Windows Questions C++

LEAVE A COMMENT