May 17, 2013 at 7:14am UTC
Saw a thread about a program to add an extra 'b' before 'B' in a file containing 'ABC'. I tried it. Here's my code:
("file1.txt" contains "ABC")
#include<iostream>
#include<fstream>
using namespace std;
int main()
{
ifstream in;
ofstream out;
in.open("file1.txt");
out.open("file2.txt");
char a;
while (!in.eof())
{
in>>a;
if (a=='B' )
{
out<<"bB";
}
else out<<a;
}
return 0;
}
It works except an extra C appears at the end.
O/P in the file:
"AbBCC"
May 17, 2013 at 7:23am UTC
while (!in.eof())
DO not use eof() for loop conditions ever. It stops too late.
In your case use
1 2 3
while (in>>a) {
if (a == 'B' ) {
//...
EDIT : Do not forger to replace file1 with file2 to make it like original thread OP wanted.
Last edited on May 17, 2013 at 7:28am UTC
May 17, 2013 at 7:27am UTC
Thanks! I'll keep that in mind.
May 17, 2013 at 7:59am UTC
What is the syntax to replace the files?
May 17, 2013 at 8:05am UTC
Last edited on May 17, 2013 at 8:06am UTC