Grupo
Manejo de Archivos en C++
Ojetivo
1. Solicita al usuario que introduzca cuántos números desea guardar.
2. Usa un bucle para recopilar los números del usuario y almacenarlos en un archivo usando `ofstream`.
3. Después de guardar los números, vuelve a abrir el archivo usando `ifstream`.
4. Lee los números del archivo y muéstralos en la consola.
5. Asegúrate de cerrar el archivo después de cada operación.
Implementa un programa que guarde una lista de números en un archivo y luego los lea.
Ejemplo de Código C++
Mostrar Código C++
#include <iostream> // Include for standard I/O
#include <fstream> // Include for file stream operations
using namespace std;
int main() {
string fileName = "numbers.txt"; // File to store the numbers
int count; // Number of values to enter
// Ask user how many numbers they want to enter
cout << "How many numbers do you want to save? ";
cin >> count;
ofstream outFile(fileName); // Open file for writing
// Check if the file was opened successfully
if (!outFile) {
cout << "Error opening file for writing." << endl;
return 1; // Exit with error
}
// Loop to write numbers to the file
cout << "Enter " << count << " numbers:" << endl;
for (int i = 0; i < count; ++i) {
int num;
cin >> num;
outFile << num << " "; // Write each number followed by a space
}
outFile.close(); // Close the output file
ifstream inFile(fileName); // Open file for reading
// Check if the file was opened successfully
if (!inFile) {
cout << "Error opening file for reading." << endl;
return 1; // Exit with error
}
// Read and display the numbers from the file
cout << "Numbers read from file:" << endl;
int num;
while (inFile >> num) {
cout << num << " "; // Output each number
}
inFile.close(); // Close the input file
cout << endl;
return 0; // End of program
}
Salida
How many numbers do you want to save? 4
Enter 4 numbers:
12
34
56
78
Numbers read from file:
12 34 56 78
Comparte este ejercicio C++