C ++: using ifstream with getline ();

Check out this program.

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

There are many characters in the Hey.txt file. Good for 1000

But my question is: Why the second time I try to print a line. Does it not print?

+4
source share
3 answers

According to the C ++ link ( here ) getline sets ios::fail when the count-1 characters were extracted. You will need to call filein.clear(); between calls to getline() .

+8
source

An idiomatic way of reading lines from a stream:

 { std::ifstream filein("Hey.txt"); for (std::string line; std::getline(filein, line); ) { std::cout << line << std::endl; } } 

Note:

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

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

+19
source

As correctly said Kerrek SB. There are 2 possibilities: 1) The second line is an empty line 2) there is no second line, and all more than 1000 characters are in one line, so the second getline nothing to do.

0
source

All Articles