[EOF Problem] Extra Character In Output

This is a discussion on [EOF Problem] Extra Character In Output within the C++ Programming forums, part of the General Programming Boards category; I'm reading characters out of a text file and printing them to the console via this code: Code: ifstream textFile; ...

  1. #1
    Young C n00b
    Join Date
    Jul 2006
    Posts
    59

    [EOF Problem] Extra Character In Output

    I'm reading characters out of a text file and printing them to the console via this code:
    Code:
    ifstream textFile;
    textFile.open(s.c_str(), ios::in);
    
    char c = NULL;
    while(!textFile.eof()) {
    	textFile >> c;
    	cout << c;
    }
    Here is what is actually in the text file:
    1234567890

    This is what gets printed:
    12345678900


    Why does it print the last character twice? What can I do to avoid it?

  2. #2
    C++ Witch laserlight's Avatar
    Join Date
    Oct 2003
    Location
    Singapore
    Posts
    21,893
    Read the FAQ on why you should not use eof() to control a loop like that (in fact, your observation is the answer why). Rather, use the result of textFile >> c.
    C + C++ Compiler: MinGW port of GCC
    Version Control System: Bazaar

    Look up a C++ Reference and learn How To Ask Questions The Smart Way

  3. #3
    Sweet
    Join Date
    Aug 2002
    Location
    Tucson, Arizona
    Posts
    1,807
    Using eof is not a good way to control a file read loop. Just use operator >>
    Code:
    while(textFile>>c){
       cout<<c;
    }
    Woop?

  4. #4
    Young C n00b
    Join Date
    Jul 2006
    Posts
    59
    Awesome answers. Thank you both for your help.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Changing the character output.
    By InFeStEd-ArCh0n in forum C++ Programming
    Replies: 7
    Last Post: 05-03-2002, 12:39 PM
  2. Slow character output...
    By |<4D4\/eR in forum C++ Programming
    Replies: 4
    Last Post: 04-16-2002, 09:10 AM
  3. extra character at end!
    By Shakespeare in forum C++ Programming
    Replies: 2
    Last Post: 03-25-2002, 12:32 PM
  4. I can't output this, no matter how hard I try
    By Zewu in forum C++ Programming
    Replies: 10
    Last Post: 01-25-2002, 08:13 PM
  5. How do I output one character??
    By kia_1998 in forum C++ Programming
    Replies: 1
    Last Post: 10-29-2001, 09:46 PM

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