Velvet Star Monitor

Standout celebrity highlights with iconic style.

updates

C++: Using ifstream with getline();

Writer Sophia Terry

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?

5 Answers

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.

7

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.

4
#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;
}
1

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.

1

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

Your Answer

Sign up or log in

Sign up using Google Sign up using Facebook Sign up using Email and Password

Post as a guest

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy