Strings replace word in file

I need to write program that reads in string from input file and whenever it finds "foo" it should replace it with "xxx" and send corrected string to output file
my result is
axxxt barefoot buffoon
axxxt barexxxt buffoon
axxxt barexxxt bufxxxn
which is wrong
it should be
axxxt barexxxt bufxxxn

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
#include <iostream>
#include <string>
#include <fstream>

using namespace std;


int main()
{
    int pos;
    string line;
    ifstream fin("out1.txt");
    ofstream fout("out2.txt");
    getline(fin,line);
    while (fin)
        {
            pos=line.find("foo",0);
            line.replace(pos,3,"xxx");
            fout<<line<<endl;
        }
        fin.close();
        fout.close();

    return 0;
}
1
2
3
4
5
6
7
8
9
10
while (fin)
        {
            pos=line.find("foo",0);
            line.replace(pos,3,"xxx");
         }

         fout<<line<<endl;

        fin.close();
        fout.close();


maybe?
Last edited on
i tried doesn't work

output is
axxxt
maybe getline would work.
Your while condition is checking the state of the stream and it probably loops infinitely. You want to check that your done replacing instead. std::string::find returns std::string::npos if it did not find a match.
Topic archived. No new replies allowed.