Grupo
Manejo de Archivos en C++
Ojetivo
1. Solicite al usuario que ingrese su nombre y edad.
2. Abra un archivo en modo de escritura usando `ofstream`.
3. Escriba la información recopilada en el archivo.
4. Cierre el archivo una vez completada la escritura.
5. Informe al usuario que su información se ha guardado.
Cree un programa que registre información en un archivo (como el nombre y la edad).
Ejemplo de Código C++
Mostrar Código C++
#include <iostream> // Include for standard input and output
#include <fstream> // Include for file output stream
#include <string> // Include for using the string class
using namespace std;
int main() {
string name; // Variable to store the user's name
int age; // Variable to store the user's age
// Prompt the user to enter their name
cout << "Enter your name: ";
getline(cin, name); // Read the full name including spaces
// Prompt the user to enter their age
cout << "Enter your age: ";
cin >> age; // Read the user's age
ofstream outFile("userdata.txt"); // Create and open a file named 'userdata.txt'
// Check if the file was opened successfully
if (outFile.is_open()) {
// Write the name and age into the file
outFile << "Name: " << name << endl;
outFile << "Age: " << age << endl;
outFile.close(); // Close the file after writing
cout << "Information saved successfully to 'userdata.txt'." << endl;
} else {
// Display an error if the file could not be opened
cout << "Error: Could not open file for writing." << endl;
}
return 0; // End of program
}
Salida
//Output Example:
Enter your name: Alice Johnson
Enter your age: 28
Information saved successfully to 'userdata.txt'.
//Content of userdata.txt:
Name: Alice Johnson
Age: 28
Comparte este ejercicio C++