[ifstream] Double reading of the last character.

Discussion in 'C++' started by Felix.leg, Feb 7, 2012.

  1. Felix.leg

    Felix.leg Guest

    Hi,

    I have got a strange behavior in my fstream library, I suppose (I'm
    using "g++ (Ubuntu 4.4.3-4ubuntu5) 4.4.3"). Even with a simple code
    like this:
    Code:
    #include <iostream>
    #include <fstream>
    using namespace std;
    int main (int argc, char **argv)
    {
    ifstream afile("chars" , ifstream::in );
    char z;
    
    while( afile.good() ) {
    afile.get(z);
    cout << " '" << z << "' ";
    }
    cout << endl;
    afile.close();
    return 0;
    }
    
    It reads right until the end of file. Then it reads the last character
    twice.

    Is my library broken? Or it is me doing it wrong?
    Felix.leg, Feb 7, 2012
    #1
    1. Advertising

  2. On 2/7/2012 11:49 AM, Felix.leg wrote:
    > I have got a strange behavior in my fstream library, I suppose (I'm
    > using "g++ (Ubuntu 4.4.3-4ubuntu5) 4.4.3"). Even with a simple code
    > like this:
    >
    Code:
    > #include<iostream>
    > #include<fstream>
    > using namespace std;
    > int main (int argc, char **argv)
    > {
    > 	ifstream afile("chars" , ifstream::in );
    > 	char z;
    >
    > 	while( afile.good() ) {
    > 		afile.get(z);
    > 		cout<<  " '"<<  z<<  "' ";
    > 	}
    > 	cout<<  endl;
    > 	afile.close();
    > 	return 0;
    > }
    > 
    > It reads right until the end of file. Then it reads the last character
    > twice.
    >
    > Is my library broken? Or it is me doing it wrong?


    See the FAQ.

    V
    --
    I do not respond to top-posted replies, please don't ask
    Victor Bazarov, Feb 7, 2012
    #2
    1. Advertising

  3. Felix.leg

    Christopher Guest

    Christopher, Feb 7, 2012
    #3
    1. Advertising

Want to reply to this thread or ask your own question?

It takes just 2 minutes to sign up (and it's free!). Just click the sign up button to choose a username and then you can ask your own questions on the forum.
Similar Threads
  1. Ridimz
    Replies:
    15
    Views:
    1,263
  2. Sydex
    Replies:
    12
    Views:
    6,429
    Victor Bazarov
    Feb 17, 2005
  3. Daniel Mark
    Replies:
    6
    Views:
    70,689
    Tim Chase
    Sep 28, 2006
  4. Kenneth
    Replies:
    2
    Views:
    371
    Rolf Magnus
    Mar 23, 2007
  5. Johny
    Replies:
    8
    Views:
    371
Loading...

Share This Page