Question

[Please don't comment on using Turbo C++. I know that it's obsolete but we are taught this way only.] Somewhat similar kind of error is here Why do I get a 'ÿ' char after every include that is extracted by my parser? - C but I couldn't relate it to my code - Well I'm a newbie.

#include<fstream.h>
#include<conio.h>
void main()
{
 clrscr();
 char ch;
 ifstream read_file;
 read_file.open("Employee.txt");
 ofstream write_file;
 write_file.open("Another.txt");

 while(!read_file.eof())
 {
 /*Also when I use, write<<read_file.get(ch) in this block instead of the two statements below, it writes some kind of address in the file. Please tell me about that too why it happens. */

  read_file.get(ch); 
  write_file<<ch; 
 }
 read_file.close();
 write_file.close();
 getch();
}

The problem I'm facing is that it appends ÿ character at the end of 'another' file.

eg: the text in "Employee" is, ID:1 Name:abc then the text it copies to "another" is: ID:1 Name:abcÿ

Was it helpful?

Solution

The eof() check won't return true once you've read the last character; it stays false until after you've tried to read past the end. So rather than checking for eof in the while-loop condition, check for it right after you read (but before you write), and then break.

(Incidentally, a bit of explanation: ÿ is the ANSI character representation of the value 0xFF, which is to say, -1. This is what get() returns to signal EOF. So if you wanted, instead of checking eof(), you could see whether the char equalled -1.)

OTHER TIPS

while(!read_file.eof())

is always wrong. You need

while (read_file.get(ch))

or

while ((ch = read_file.get()) != EOF)
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top