0

I am pretty new to C++ programming. My objective is to copy the content of one file into another file.

My code like below:

#include<iostream.h>
#include<stdio.h>
#include<conio.h>
#include<stdlib.h>
#include<fstream.h>

int main(){
    ifstream file1;
    ofstream file2;
    char ch;
    char sfile[10], tfile[10];
    cout<<"\nEnter the source filename: ";
    cin>>sfile;
    cout<<"\nEnter the target filename: ";
    cin>>tfile;

    file2.open(sfile);
    file2<<"hello world";
    file2.close();

    file1.open(sfile);
    file2.open(tfile);

    while(!file1.eof()){
        file1.get(ch);
        cout<<ch;
        if(file1.get(ch) == " "){
            continue;
        }
    file2<<ch;
    }
    file1.close();
    file2.close();
    return 0;
}

However I am not getting the correct result in the output file. It should have been helloworld but I am getting el olÿ in the output file.

Not sure what wrong am I doing here. Can anyone please help me in this?

danglingpointer
  • 4,708
  • 3
  • 24
  • 42
Leo
  • 5,017
  • 6
  • 32
  • 55
  • 1
    https://stackoverflow.com/questions/5431941/why-is-while-feof-file-always-wrong – Mat Nov 27 '17 at 11:52
  • 1
    Possible duplicate of [Why is “while ( !feof (file) )” always wrong?](https://stackoverflow.com/questions/5431941/why-is-while-feof-file-always-wrong) –  Nov 27 '17 at 11:53
  • 2
    Also, don't call file1.get() multiple times per iteration, or you are moving the file pointer forward too much. –  Nov 27 '17 at 11:54
  • 3
    What do you think happens when you do `file1.get(ch)` *twice* in a single loop? – Some programmer dude Nov 27 '17 at 11:54

2 Answers2

2

There are several problems here:

  1. Don't use std::ifstream::eof() as loop condition.

  2. Don't compare a character against a string literal. Use single quotes for character literals.

  3. Don't call get() twice, you'll lose half of the characters.

Change the loop to:

while (file1.get(ch)) {
    cout << ch;
    if (ch == ' ') {
        continue;
    }
    file2 << ch;
}
iBug
  • 35,554
  • 7
  • 89
  • 134
0

if you are code is correct , the tfile has "helloworld" in it. but it wont be displayed as such when you open it directly. you can check contents of tfile by using the code above to display the data.

krishna
  • 3
  • 4