find and replace from a file

hello
i want to enter a file and find a word at the file a whole and replace every on of it with anther word and this i was made it to find a word from a file can i modify it to replace a 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
 #include <iostream>
#include <string>
#include <fstream>
#include <sstream>
using namespace std;
string search (string filename, string word)
{
       int lineNum=1;
        string line;

    ifstream file;
    file.open(filename.c_str(),ios::);
    if (file.is_open())
        {
            while(getline(file,line))
                {
                    istringstream iss(line);
                    string testWord;
                    while (iss>>testWord)
                   {
                    if (testWord==word)
                       {
                            return line;
                        }
                   }
                   ++lineNum;
                }
            file.close();
        }
        else {cout<<"error"<<endl;}

}
int main()
{
    string filename;
    string searchWord;
    cin>>filename;
    cin>>searchWord;
    cout<<search(filename,searchWord);
    return 0;
}
Note: This looks like a followup question to http://www.cplusplus.com/forum/beginner/127100/

http://www.cplusplus.com/reference/string/string/find/ has an another example of finding a word.

http://www.cplusplus.com/reference/string/string/replace/

One function should preferably do only one thing. Opening a file and operating on it are two things. Besides, what if the function should standard input instead of a file?
1
2
3
4
5
6
7
8
9
10
11
12
13
size_t foo( istream & fin, ostream & fout )
{
  size_t count = 0;  // replacement events
  double value = 0.0;
  while ( fin >> value ) {
    if ( value < 7.0 ) {
      value = 42.0;
      ++count;
    }
    fout << value << '\n';
  }
  return count;
}

Obviously, foo() is not about replacing words in text. It is just an example of an idea.

string::find() can tell a location of subsequence within a line, but "bobcat" contains a "cat". Is that ok?

If you want to match proper words, then the characters right before and after a match cannot be from alphabet. Thus, a line starts with "cat*", ends with "*cat", or contains "*cat*", where the '*' is whitespace or punctuation. For this purpose there are regular expressions in the C++11 standard.
Topic archived. No new replies allowed.