'C++: Using ifstream with getline();

Check this program

ifstream filein("Hey.txt");
filein.getline(line,99);
cout<<line<<endl;
filein.getline(line,99);
cout<<line<<endl;
filein.close();

The file Hey.txt has alot of characters in it. Well over a 1000

But my question is Why in the second time i try to print line. It doesnt get print?



Solution 1:[1]

According to the C++ reference (here) getline sets the ios::fail when count-1 characters have been extracted. You would have to call filein.clear(); in between the getline() calls.

Solution 2:[2]

The idiomatic way to read lines from a stream is this:

std::ifstream filein("Hey.txt");

for (std::string line; std::getline(filein, line); ) 
{
    std::cout << line << std::endl;
}

Notes:

  • No close(). C++ takes care of resource management for you when used idiomatically.

  • Use the free std::getline, not the stream member function.

Solution 3:[3]

#include<iostream>
using namespace std;
int main() 
{
ifstream in;
string lastLine1;
string lastLine2;
in.open("input.txt");
while(in.good()){
    getline(in,lastLine1);
    getline(in,lastLine2);
}
in.close();
if(lastLine2=="")
    cout<<lastLine1<<endl;
else
    cout<<lastLine2<<endl;
return 0;
}

Solution 4:[4]

As Kerrek SB said correctly There is 2 possibilities: 1) Second line is an empty line 2) there is no second line and all more than 1000 character is in one line, so second getline has nothing to get.

Solution 5:[5]

An easier way to get a line is to use the extractor operator of ifstream

    string result;
    //line counter
    int line=1;
    ifstream filein("Hey.txt");
    while(filein >> result)
    { 
      //display the line number and the result string of reading the line
      cout << line << result << endl;
      ++line;
    }

One problem here though is that it won't work when the line have a space ' ' because it is considered a field delimiter in ifstream. If you want to implement this kind of solution change your field delimiter to e.g. - / or any other field delimiter you like.

If you know how many spaces there is you can eat all the spaces by using other variables in the extractor operator of ifstream. Consider the file has contents of first name last name.

    //file content is: FirstName LastName
    int line=1;
    ifstream filein("Hey.txt");
    string firstName;
    string lastName;
    while(filein>>firstName>>lastName)
    {
      cout << line << firstName << lastName << endl;
    }

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Roman Kutlak
Solution 2 Matheus Monteiro
Solution 3 Junyu lu
Solution 4 BigBoss
Solution 5