-4

When I copying the content of file Source.txt, which include only the word "Life", to another file Target.txt. It only copy the "EI" not "Life".why? The following

Blockquote

is the code that i tried. is another way to copy one file content to another file. and also explain the following why it's happen? Thanks in advance. Great Confusion.

Source File include the following text: Life Copied Files from Source File is: EI

char ch;
ifstream source("Source.txt");
ofstream target("Target.txt");
while(source.eof()==false)
{
 source.get(ch);
 target<<ch
  • Read [Why is `iostream::eof` inside a loop condition considered wrong?](https://stackoverflow.com/questions/5605125/why-is-iostreameof-inside-a-loop-condition-considered-wrong). – molbdnilo Dec 03 '18 at 09:49

1 Answers1

1

The correct code is

char ch;
ifstream source("Source.txt");
ofstream target("Target.txt");
while(source.get(ch))
{
 target<<ch;
}

eof is only true after you read and it fails (because of eof). It's not generally true when you are at the end of file, i.e. if the next read will fail because of end of file. Because of this reason it's almost never correct to use eof in a while loop condition.

More detail

john
  • 85,011
  • 4
  • 57
  • 81