← Back to Streams
Question 659
Replace a Word
Replace a Word
Write a functionint replaceWord(const string& filename, const string& from, const string& to)that replaces every whole word equal tofromwithtoinside a text file and returns how many words were replaced. The file contains words separated by single spaces on one line, ending with a newline. Read the words with>>, replace the matching ones, then reopen the file inios::out | ios::truncmode and write the words back on one line separated by single spaces, with no space before the first word, followed by a newline. Return the number of replacements (0 iffromnever appears; the file is then rewritten unchanged). The test prints the returned count on its own line, then every line of the file. For a file containinghello there helloand the callreplaceWord("words_a.txt", "hello", "hi")it prints the output shown in Expected Output. Do NOT write a main function.
Expected Output:
2 hi there hi 0 foo bar
= newline. The output ends with a newline — print one after the last line.
Hints4 available
Sign in to use hintsTopics:
Streamsfstream
1
Tab to indent (Esc then Tab to move on) · Ctrl+Enter to run · Shift+Alt+F to format · Ctrl+Space to expand shortcuts (cout, fori)
Your Output
Run your code to see the output here...
Test Cases
Run your code to see test case results.