0

Test file wrote like

   Sat Aug 10 22:03:09 2019
   Test completed

First i used in.eof(), but someone told me do never use thoes in.eof().

enter code here
#include <fstream>
#include <iostream>
#include <string>

int main() {
  //test.txt is a test file. 
  std::ifstream in("test.txt");

if (!in.is_open()) {
   std::cout << "file not found" << std::endl;
return 0;
}

std::string s;
while (in) {
getline(in, s);
std::cout << s << std::endl;
  }

  return 0;
}

I'd expect the result like

   Sat Aug 10 22:03:09 2019
   Test completed

But the result is

   Sat Aug 10 22:03:09 2019
   Test completed
   Test completed
acraig5075
  • 9,913
  • 3
  • 29
  • 45
papayetoo
  • 25
  • 6
  • Try `while(getline(in, s))` instead of `while (in) { getline(in, s)...`. – pschill Aug 12 '19 at 09:36
  • 1
    getline doesn't read the last line twice, the last getline fails, leaving the `s` variable unchanged. Fix your loop and the problem will go away. – john Aug 12 '19 at 09:52
  • Possible duplicate of [Why is iostream::eof inside a loop condition (i.e. \`while (!stream.eof())\`) considered wrong?](https://stackoverflow.com/questions/5605125/why-is-iostreameof-inside-a-loop-condition-i-e-while-stream-eof-cons) – Toby Speight Aug 12 '19 at 10:06

3 Answers3

2

The standard way to do what you want is

for (std::string s; std::getline(in, s);)

The issue may be related with the new line symbol (\n) at the end of the file.

Nestor
  • 652
  • 3
  • 12
1

Loop while getline is successfull and not while the istream is valid.

while (getline(in, s)) {
  std::cout << s << std::endl;
  }
acraig5075
  • 9,913
  • 3
  • 29
  • 45
1

The problem is with this part of the code, just after the last successful read:

while (in) {          // succeeds
    std::getline(in, s);   // fails (EOF), and s is unchanged

This is exactly equivalent to Why is iostream::eof inside a loop condition (i.e. while (!stream.eof())) considered wrong?.

The fix is to make the getline() result part of the condition:

while(std::getline(in, s)) {
Toby Speight
  • 23,550
  • 47
  • 57
  • 84