I would like to read a file which has several lines, and then search for a specific line, if that line is found, I would like to replace that line with some other value, how do i do it?
Here is what have now:
#include <string>
using namespace std;
int main()
{
string line;
ifstream myfile( "file.txt" );
if (myfile)
{
while (getline( myfile, line ))
{
if (line == "my_match")
{
//cout << "found";
... here i would like to replace "my_match" with some other value
}
}
myfile.close();
}
else cout << "error";
return 0;
}
If you want comments on how to make the code neater, Code Review is where you want to be.
Assuming you’re working with standard input and output, and will do redirection and such in a different language: yes, what you’re doing is a possible solution. You’re not telling us what you want to replace it with, but the following should do it fine:
I’d say that the biggest problem with this is it not being very generic; if you only want to match a line depending on a more complicated predicate, you’re best off writing a dedicated function (or regex) for that; same for having the replacement depend on the line. For example, in your loop you could have:
And then you could define:
Note that this makes a copy for each line, though, which may be expensive (depends on requirements and file size).