-1

Possible Duplicate:
Why is iostream::eof inside a loop condition considered wrong?

i used this code to replace the first " with `` and the second one with '' everything works just fine except it runs through the loop one more time after the last character is read and that makes the program print another character

#include <fstream>
#include <iostream>
using namespace std ;
void main ()
{
    ifstream infile;
    infile.open("infile.txt");
    ofstream outfile;
    outfile.open("outfile.txt");
    char c ;

    int i = 0 ;
    while ( !infile.eof() )
    { 
        infile.get(c)
            if (c=='\"')
            {
                i++ ;
                if (i%2==0)
                    outfile<<"\'\'";
                else 
                    outfile<<"``";
            }
            else 
                outfile<<c;
    }
    outfile.close();
    infile.close();
}
Community
  • 1
  • 1

1 Answers1

4

Don't do while ( !infile.eof() ) - this only checks if the previous read hit the end of the file, not if the next one will. So when the last character is read, it loops round again, sees that it hasn't hit the end of file yet and then proceeds to read another character even though there isn't another character to read. Your c will have the same value from the previous iteration.

Instead, do this:

while (infile.get(c))
{
  // ... 
}

This will read a character from the file and then, if that was succesful, will do something with that character.

Joseph Mansfield
  • 100,738
  • 18
  • 225
  • 303
  • The reason this works isn't obvious by reading the documentation for [`std::basic_istream::get`](http://en.cppreference.com/w/cpp/io/basic_istream/get). I figured it out, but it might be worth including an explanation. – Mark Ransom Jan 29 '13 at 18:55
  • @MarkRansom: The problem there is the phrase "_the_ documentation". One should read a proper C++ book to gain an understanding of the language that _cannot_ be garnered from an API reference. – Lightness Races in Orbit Jan 29 '13 at 19:03
  • @Non-StopTimeTravel, I can't fault your suggestion at all. It's still useful to have that kind of information here on StackOverflow though. – Mark Ransom Jan 29 '13 at 20:15
  • @MarkRansom: I can't disagree with that at all. :) – Lightness Races in Orbit Jan 29 '13 at 20:24