simple file i/o

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"

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
Thanks! I'll keep that in mind.
What is the syntax to replace the files?
It is OS specific, so you should look into your OS headers.
Or you can use boost::filesystem lib to handle files. (Of course you should have boost installed)

for windows: include windows.h and use http://msdn.microsoft.com/en-us/library/windows/desktop/aa363851%28v=vs.85%29.aspx
Last edited on
Topic archived. No new replies allowed.