SOS-Hello Anybody there(Strings)

Im using fstream and strings-working with text documents
what code does one use if the user wants to swap a word or words in a
text file, eg the user wants to swap the word "here" in a text file with the word "there" without using predefined functions such as "strswap".......thanks
closed account (28poGNh0)
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
# include <iostream>
# include <fstream>
using namespace std;

int main()
{
    ifstream in("test.txt");

    string fileData,newFileData="",wordToFind = "who'",wordToChange = "here";


    if(in)
    {
        while(in)
            fileData += in.get();

        size_t count;
        bool pass = false;

        for(size_t i=0;i<fileData.size()-wordToFind.size()+1;i++)
        {
            count = 0;

            for(size_t j=0;j<wordToFind.size();j++)
            {
                if(fileData[i+j]==wordToFind[j])
                    count++;

                else break;
            }if(count==wordToFind.size())
            {
                string tmpStr = (newFileData + wordToFind);
                newFileData += wordToChange;

                for(size_t j=tmpStr.size();j<fileData.size();j++)
                {
                    newFileData += fileData[j];
                }pass = true;
                break;
            }newFileData += fileData[i];
        }
        if(pass)
        {
            in.close();
            
            ofstream out("test.txt");
            
            out << newFileData;
            
            out.close();
        }else cout << "Word to Find is not existed" << endl;

    }else cout << "Cannot find this file" << endl;
    
    cout << "End of program" << endl;

    return 0;
}

thanks.....
just one small complication, how would I get an input from the user as to which
word to change, and which word to put in place of the changed word.......
cout<<"Enter word to change:"
cin>>ChangeWord;
cout<<"Enter word to replace:"
cin>>ReplaceWord;

Last edited on
closed account (28poGNh0)
put
1
2
3
4
5
6
string fileData,newFileData="",wordToFind ,wordToChange;

    cout << "Enter word to change -> ";
    cin >> wordToChange;
    cout << "Enter word to replace -> ";
    cin >> wordToFind;

instead of
string fileData,newFileData="",wordToFind = "who'",wordToChange = "here";

It's an easy one
Last edited on
Topic archived. No new replies allowed.