CJCoding With Joseph
15free / daySign inCreate account

Replace a Word

Write a function int replaceWord(const string& filename, const string& from, const string& to) that replaces every whole word equal to from with to inside 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 in ios::out | ios::trunc mode 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 if from never 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 containing hello there hello and the call replaceWord("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
Topics:
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.