Search and replace in text file

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?

Thanks

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
#include <string>
#include <fstream>
#include <iostream>

using namespace std; 

int main() {

	string line; 
	ifstream myfile("test.txt");
	if (!myfile.is_open())
	{
		cout << "cant open";
		return 1;
	}
	ofstream myfile2("outfile.txt");

	std::string str("");
	std::string str2("Electric");
	while (getline(myfile, line))
	{
		std::size_t found = str.find(str2);

		found = str.find("Electric");
		if (found != std::string::npos) {
			str.replace(str.find(str2), str2.length(), "");
		
			std::cout << found << "\n";

		}
			

		
		cout << str << "\n";
	}

		remove("test.txt");

		rename("outfile.txt", "test.txt");
}
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.
I updated it with some help, but I'm still not getting it to work.

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
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?

Last edited on
Topic archived. No new replies allowed.