How do I replace a word from a .txt file?

I'm trying to make a program that will find a certain word from a text file, then replace that word with something else. Currently, I'm outputting the result in console. My main problem is how to replace a word with another word.




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
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
#include <iostream>
#include <string>
#include <fstream>

using namespace std;
int main ()
{

	string str[1000];
	string header;
	string content = "This is the content area for the website";
	string footer;
	string sidebar;
	string source[2];
	int pos[5];

	fstream file;
	size_t found;

	file.open ("Template.html");



		for (int i=0; i<1000; i++)
		{
			getline(file,str[i]);
		}



	for (int i = 0; i<1000; i++)
	{
			found = str[i].find("header");
			if (found!=string::npos)
			pos[0] = found;

			found = str[i].find("content");
			if (found!=string::npos)
			pos[1] = found;
						
			found = str[i].find("sidebar");
			if (found!=string::npos)
			pos[2] = found;

			found = str[i].find("footer");
			if (found!=string::npos)
			pos[3] = found;
						
			found = str[i].find("source1");
			if (found!=string::npos)
			pos[5] = found;

			found = str[i].find("source2");
			if (found!=string::npos)
			pos[6] = found;

	}

			

		for (int i = 0; i<1000; i++)
		{	
			str[i].replace(pos[1],5,content);  <-- My problem. I randomly entered 5
		}



	
		for (int i=0; i<1000; i++)
		{
			cout<<str[i];

		}
	




	return 0;


}
When you're reading in a file, you declare it as ifstream and not fstream (and when you're writing to a file, you declare it as ofstream).

Moreover, when you finish processing your file, you need to close() it.

As for replace(), make sure you're using it correctly:
http://www.cplusplus.com/reference/string/string/replace/

Moreover, find() searches a string, so you don't give it a char!
http://www.cplusplus.com/reference/string/string/find/
Last edited on
I'm still having trouble with replace().
1
2
3
4
5
6
7
8
9
10
11
12
13
14
#include <string>

std::string replace_substrings( std::string str,
                                const std::string& original_substring,
                                const std::string& new_substring )
{
    auto pos = str.find( original_substring ) ;
    while( pos != std::string::npos )
    {
        str.replace( pos, original_substring.size(), new_substring ) ;
        pos = str.find( original_substring, pos + new_substring.size() ) ;
    }
    return str ;
}
Topic archived. No new replies allowed.