[try Beta version]
Not logged in

 
Strings replace word in file

May 4, 2010 at 5:34pm
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;
}
May 4, 2010 at 5:56pm
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 May 4, 2010 at 5:57pm
May 4, 2010 at 6:01pm
i tried doesn't work

output is
axxxt
May 4, 2010 at 6:15pm
maybe getline would work.
May 4, 2010 at 6:21pm
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.