merging two files into third file

Can anyone tell why the last alphabet of both file print twice in third file?

#include<iostream>
#include<fstream>

int main()
{
char ch1;

std::fstream rfile;
std::fstream wfile;
std::ofstream qfile;

rfile.open("1.txt");
if(!rfile)
{
std::cout<<"Error";
}

wfile.open("2.txt");
if(!wfile)
{
std::cout<<"Error";
}

qfile.open("3.txt");
if(qfile)
{
while(rfile.eof()==0)
{

rfile>>ch1;
qfile<<ch1;
}

while(wfile.eof()==0)
{

wfile>>ch1;
qfile<<ch1;
}

}
return 0;

}
If i write "wahaj" in first file and "ali" in the second file ,then in the third file its like "wahajjalii".
Don't use the eof() method to test for end of file. Think about it - it isn't going to go "true" until you have tried and failed to read the file (with rfile >> ch1). But if the latter failed then it had nothing new to put in ch1, so it just writes what it had previously to qfile.

Test on the condition of the stream after an attempted read instead.
1
2
3
4
while(rfile>>ch1)
{
   qfile << ch1;
}


Similarly for the other filestream.


BTW - the stream extractor >> will, by default, ignore spaces in the input file. Is that what you intended?
Last edited on
ok got it .Thanks alot , What about space between these words?
swahajali wrote:
What about space between these words?


You can either use std::noskipws if you want to continue using stream extractors:
while( rfile >> std::noskipws >> ch1 )

or you could just use get()
while( rfile.get( ch1 ) )
Its working but it applies only one file for example if i write "syed wahaj" is 1 file and "ali" in second file , then its look "syed wahajali"
Last edited on
If you want a space between the output from one file and the next then just output one explicitly:
qfile<<' ';

If you want to write a space only if there isn't one at the end of the first file then
if ( ch1 != ' ' ) qfile<<' ';
(presuming ch1 to have the last character read successfully from the first file.
got it . Thanks alot
Topic archived. No new replies allowed.