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.
I am guessing that for string, std::getline, it extracts string for 1st, 2nd and when it tries to extract the 3rd time it sees eof so it extracts just before eof.
The next time we try to extract it, just encounters eof so it didn't extract anything and set fail-bit.
string str didn't get modified, so when we try to print it, only the string last extracted gets printed.
I don't know if what I’m thinking is right...
Also I can’t make any such case regarding istream::getline(), C-style char array.