Character Replacement

Character replacement program

You can use outputFile.put(char) to insert a single char into an output file.

Write a program that reads the contents of a file named example.txt. The program should allow the user to specify a character to be replaced and a character to replace it with. The program should then create a new file named modified.txt, where all occurrences of the specified character are replaced with the new character. The program should ensure that all file operations are handled appropriately.

Answer

#include <iostream>
#include <fstream>
#include <string>

int main() {
    std::ifstream inFile("example.txt");
    if (!inFile) {
        std::cerr << "Error: Could not open the file example.txt." << std::endl;
        return 1;
    }

    std::ofstream outFile("modified.txt");
    if (!outFile) {
        std::cerr << "Error: Could not create the file modified.txt." << std::endl;
        return 1;
    }

    char charToReplace, replacementChar;
    std::cout << "Enter the character to replace: ";
    std::cin >> charToReplace;
    std::cout << "Enter the replacement character: ";
    std::cin >> replacementChar;

    char ch;
    while (inFile.get(ch)) {
        if (ch == charToReplace) {
            ch = replacementChar;
        }
        outFile.put(ch);
    }

    inFile.close();
    outFile.close();

    std::cout << "File modification complete. Check modified.txt for the result." << std::endl;

    return 0;
}
Questions