merging two files into third file

Nov 20, 2018 at 9:01am
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".
Nov 20, 2018 at 9:17am
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 Nov 20, 2018 at 9:22am
Nov 20, 2018 at 9:21am
ok got it .Thanks alot , What about space between these words?
Nov 20, 2018 at 9:36am
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 ) )
Nov 21, 2018 at 7:55am
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 Nov 21, 2018 at 7:57am
Nov 21, 2018 at 8:57am
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.
Nov 21, 2018 at 9:35am
got it . Thanks alot
Topic archived. No new replies allowed.