I'm trying to search and replace in a text file but it isn't working, I know its simple feel like im missing something small. I'm trying to replace Electric with a non-space character. Can anyone help me out?
At line 20, a line is read from the file into the string line. You need to do the search and replace in that string line. Then write the line to the output file myfile2.
int main()
{
ifstream is("test.txt");
if (!is)
return -1;
ofstream os("outfile.txt");
if (!os)
return -2;
string s;
while (getline(is, s)) // read from is
{
std::string str("");
std::string str2("Electric");
std::size_t s = str.find(str2);
if (s != std::string::npos) {
str.replace(str.find(str2), str2.length(), "");
}
os << s << endl; // the searched string is now removed from s: write it to os
}
remove("test.txt");
rename("outfile.txt", "test.txt");
return 0;
}
That code is very hard to read - single letter names such as 's' are difficult to follow.
But still, I don't see anywhere at all where the string s is searched for the word "Electric".
Also the use of another variable with a different type but also named s at line 18 is surely creating even more problems.
If you create an empty string named str, just what do you think will be found inside it?