Thread: [EOF Problem] Extra Character In Output

  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
    28,413
    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.
    Quote Originally Posted by Bjarne Stroustrup (2000-10-14)
    I get maybe two dozen requests for help with some sort of programming or design problem every day. Most have more sense than to send me hundreds of lines of code. If they do, I ask them to find the smallest example that exhibits the problem and send me that. Mostly, they then find the error themselves. "Finding the smallest program that demonstrates the error" is a powerful debugging tool.
    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,820
    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, 01: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, 09:13 PM
  5. How do I output one character??
    By kia_1998 in forum C++ Programming
    Replies: 1
    Last Post: 10-29-2001, 10:46 PM