string.find for multiple matches per line
hello all,
this is my first post here.
I need help regarding searching and replacing strings on a textfile on multiple matches per line.
For example i have a file
original_file.txt
I am here.
you are here.
If I am here and you are here, then we are both here.
|
and my code for search and replace
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 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44
|
#include <iostream>
#include <string>
#include <fstream>
using namespace std;
#define file1 "original_file.txt"
#define file2 "outputfile.txt"
int main()
{
string str2 ("here");
string str ("there");
string line;
int offset;
ifstream infile(file1);
ofstream outfile(file2);
if(!infile)
{
cerr << "Could not open: " << file1 << endl;
return 1;
}
while(!infile.eof())
{
getline(infile, line);
if((offset = line.find(str2, 0)) != string::npos)
{
line.replace(offset, str2.length(), str);
}
outfile << line << endl;
}
infile.close();
outfile.close();
return 0;
}
|
with this code my output file is
outputfile.txt
I am there.
you are there.
If I am there and you are here, then we are both here.
|
here, arises my problem. The code above is unable to search and replace str2 more than once per line.
I do not have control on the number of occurence of str2 per line. So it has to be dynamic.
Can you guys help me out please?
Any input is greatly appreciated.
thank you
Why don't you just replace if by while on line 31 ?
if we change it to while, it will cause an endless loop.
but you gave me an idea though...
main idea is to loop .find in the entire line
Topic archived. No new replies allowed.