Grupo
Manejo de Archivos en C++
Ojetivo
1. Solicite al usuario que introduzca el nombre del archivo, la palabra a buscar y la palabra de reemplazo.
2. Abra el archivo con `ifstream` y lea todo el contenido línea por línea.
3. Reemplace cada ocurrencia de la palabra de destino con la palabra de reemplazo.
4. Escriba el contenido actualizado en el mismo archivo o en uno diferente con `ofstream`.
5. Muestre un mensaje confirmando que se realizaron los reemplazos.
Cree un programa que busque una palabra en un archivo y la reemplace.
Ejemplo de Código C++
Mostrar Código C++
#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
}
Salida
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'.
Comparte este ejercicio C++