Find and Replace a Word in a File Using C++

In this exercise, you will create a C++ program that searches for a specific word in a text file and replaces it with another word. This task will help you strengthen your understanding of file handling and string manipulation in C++. The program will prompt the user to enter the name of the file, the word to be searched, and the replacement word. Then, it will read the file content, perform the replacement, and write the updated content back to the same file or a new file. This kind of operation is commonly used in text processing tools and document editors.

Group

File Management in C++

Objective

1. Ask the user to enter the file name, the word to search for, and the replacement word.
2. Open the file using `ifstream` and read all content line by line.
3. Replace every occurrence of the target word with the replacement word.
4. Write the updated content to the same file or a different file using `ofstream`.
5. Display a message confirming the replacements were made.

Create a program that searches for a word in a file and replaces it.

Example C++ Exercise

 Copy C++ Code
#include <iostream>         // Include for input and output
#include <fstream>          // Include for file handling
#include <string>           // Include for string manipulation

using namespace std;

int main() {
    string fileName;         // Variable to store file name
    string wordToFind;       // Word to search in the file
    string wordToReplace;    // Word to replace with

    // Ask user for file name and the words to find and replace
    cout << "Enter the file name: ";
    cin >> fileName;
    cout << "Enter the word to find: ";
    cin >> wordToFind;
    cout << "Enter the word to replace it with: ";
    cin >> wordToReplace;

    ifstream inFile(fileName);   // Open the file for reading

    // Check if the file opened successfully
    if (!inFile) {
        cout << "Error: Cannot open the file." << endl;
        return 1;   // Exit with error
    }

    string line;                // Variable to store each line
    string fileContent = "";    // String to hold the full content

    // Read the file line by line
    while (getline(inFile, line)) {
        size_t pos = 0;

        // Replace all occurrences of the word in the current line
        while ((pos = line.find(wordToFind, pos)) != string::npos) {
            line.replace(pos, wordToFind.length(), wordToReplace);
            pos += wordToReplace.length(); // Move past the replaced word
        }

        fileContent += line + "\n"; // Append modified line to the full content
    }

    inFile.close();  // Close the input file

    ofstream outFile(fileName); // Reopen the file for writing (overwriting)

    // Write the modified content back into the file
    outFile << fileContent;
    outFile.close();  // Close the output file

    // Confirm to the user
    cout << "All occurrences of '" << wordToFind << "' have been replaced with '" << wordToReplace << "'." << endl;

    return 0;   // End of program
}

 Output

Enter the file name: notes.txt
Enter the word to find: hello
Enter the word to replace it with: hi
All occurrences of 'hello' have been replaced with 'hi'.

Share this C++ Exercise


More C++ Programming Exercises of File Management in C++

Explore our set of C++ Programming Exercises! Specifically designed for beginners, these exercises will help you develop a solid understanding of the basics of C++. From variables and data types to control structures and simple functions, each exercise is crafted to challenge you incrementally as you build confidence in coding in C++.

  • Save and Load a List of Numbers from a File in C++

    In this exercise, you will create a C++ program that allows the user to input a list of numbers, save them to a text file, and then read and display those numbers from the file. Th...

  • Count the Number of Lines in a Text File Using C++

    This exercise guides you through the process of writing a C++ program that reads a text file and counts the number of lines it contains. This is a fundamental operation when analyz...

  • Sort the Lines of a Text File Using C++

    This exercise involves creating a C++ program that reads all lines from a text file, sorts them in alphabetical order, and then displays the sorted lines on the screen. Sorting fil...

  • Delete a Specific File Using C++

    In this exercise, you will write a C++ program that deletes a specific file from the system using file handling operations. Managing files programmatically is an essential skill in...

  • ATM Transaction Logger in C++

    In this exercise, you will develop a simple ATM simulator in C++ that logs every transaction to a file. Logging is a vital component in real-world applications, especially in banki...

  • Read and Display a Text File Using C++

    In this C++ exercise, you will create a program that reads the contents of a text file and prints them to the console. This task demonstrates how to work with file input streams in...