Strings and Swap

Alrite, Is there a code, using fstream and string that allows
the user to swap a string variable with another string in a text file..
eg; if the user wanted to change/swap the word "here" in a text file to
"there" how would one code this......thanks

My thesaurus tells me that a synonym for swap is replace: http://www.cplusplus.com/reference/string/basic_string/replace/ how does that work for ya?
Last edited on
Could you give me a more straight forward approach
I think this is probably one of the more basic find+replace things you can do:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
#include <fstream>
#include <string>

int main()
{
    std::ifstream fin("input.txt");
    std::ofstream fout("output.txt");
    
    std::string oldWord("here");
    std::string newWord("there");
    
    std::string line;
    while( fin.good() )
    {
        getline( fin, line);
        size_t pos = line.find( oldWord );
        if (pos != std::string::npos)
            line.replace(pos, oldWord.size(), newWord)
            
        fout << line << std::endl;
    }
    
    return 0;
}
Last edited on
Topic archived. No new replies allowed.