C++ reading file odd behaviour

This is a discussion on C++ reading file odd behaviour within the C++ Programming forums, part of the General Programming Boards category; 1) What's the difference between: myfile.peek() != EOF and !myfile.eof() if I declare ifstream myfile("test.txt") ? 2) test.txt Code: 12 ...

  1. #1
    Registered User
    Join Date
    Aug 2009
    Posts
    6

    C++ reading file odd behaviour

    1) What's the difference between:

    myfile.peek() != EOF and !myfile.eof() if I declare ifstream myfile("test.txt")?


    2) test.txt
    Code:
    12 05 2005 dad da ada
    12 01 2001 d d ddadda
    04 11 2005 s s s
    12 05 2005 dad da ada
    test.cpp
    Code:
    #include <iostream>
    #include <fstream>
    
    using namespace std;
    
    int main()
      {
        string a, b, c, d;
        ifstream myfile;
        myfile.open("test.txt");
        if (myfile.is_open())
          {
            while (myfile.peek() != EOF)
              {
                getline(myfile, a, ' ');
                getline(myfile, b, ' ');
                getline(myfile, c, ' ');
                getline(myfile, d, '\n');
                cout << a << ' ' << b << ' ' << c << ' ' << d << endl;
               }     
            myfile.close();
          }
      }
    If "myfile.peek() != EOF" is used, the output is:
    Code:
    12 05 2005 dad da ada
    12 01 2001 d d ddadda
    04 11 2005 s s s
    12 05 2005 dad da ada
    However If "!myfile.eof()" is used, the output has an extra line with first word truncated:
    Code:
    12 05 2005 dad da ada
    12 01 2001 d d ddadda
    04 11 2005 s s s
    12 05 2005 dad da ada
     05 2005 dad da ada
    Anybody knows why?

  2. #2
    Registered User
    Join Date
    Sep 2004
    Location
    California
    Posts
    3,246
    bit∙hub [bit-huhb] n. A source and destination for information.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. opening empty file causes access violation
    By trevordunstan in forum C Programming
    Replies: 10
    Last Post: 10-21-2008, 11:19 PM
  2. Can we have vector of vector?
    By ketu1 in forum C++ Programming
    Replies: 24
    Last Post: 01-03-2008, 04:02 AM
  3. Game Pointer Trouble?
    By Drahcir in forum C Programming
    Replies: 8
    Last Post: 02-04-2006, 01:53 AM
  4. System
    By drdroid in forum C++ Programming
    Replies: 3
    Last Post: 06-28-2002, 10:12 PM

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21