Grupo
Manejo de Archivos en C++
Ojetivo
1. Cree un programa que simule un cajero automático sencillo con opciones para depositar o retirar dinero.
2. Para cada operación, escriba una entrada de registro en un archivo llamado "atm_log.txt".
3. Cada entrada de registro debe incluir el tipo de operación, el importe y una marca de tiempo.
4. Use condicionales para garantizar que el saldo no sea negativo durante el retiro.
5. Muestre el saldo actual después de cada operación.
Desarrolle un programa que registre las operaciones del cajero automático en un archivo de registro.
Ejemplo de Código C++
Mostrar Código C++
#include <iostream> // For standard input and output
#include <fstream> // For file operations
#include <ctime> // For timestamp generation
using namespace std;
int main() {
ofstream logFile("atm_log.txt", ios::app); // Open file in append mode
double balance = 1000.0; // Initial balance
int choice;
double amount;
// Check if the file opened successfully
if (!logFile.is_open()) {
cout << "Error: Could not open log file." << endl;
return 1;
}
// Display ATM menu
cout << "ATM Simulator" << endl;
cout << "1. Deposit" << endl;
cout << "2. Withdraw" << endl;
cout << "Enter your choice: ";
cin >> choice;
// Get current time
time_t now = time(0);
char* dt = ctime(&now); // Convert time to string
if (choice == 1) {
// Deposit operation
cout << "Enter amount to deposit: ";
cin >> amount;
balance += amount; // Update balance
logFile << "Deposit: +" << amount << " | Time: " << dt; // Log transaction
cout << "Deposit successful. Current balance: $" << balance << endl;
} else if (choice == 2) {
// Withdrawal operation
cout << "Enter amount to withdraw: ";
cin >> amount;
if (amount > balance) {
// Check for insufficient funds
cout << "Insufficient funds." << endl;
logFile << "Withdrawal failed: $" << amount << " | Reason: Insufficient funds | Time: " << dt;
} else {
balance -= amount; // Deduct amount from balance
logFile << "Withdrawal: -" << amount << " | Time: " << dt; // Log transaction
cout << "Withdrawal successful. Current balance: $" << balance << endl;
}
} else {
// Invalid option
cout << "Invalid option." << endl;
}
logFile.close(); // Close the file
return 0; // Exit the program
}
Salida
//Output Example:
ATM Simulator
1. Deposit
2. Withdraw
Enter your choice: 1
Enter amount to deposit: 300
Deposit successful. Current balance: $1300
//atm_log.txt content after operation:
Deposit: +300 | Time: Wed Apr 16 14:55:30 2025
Comparte este ejercicio C++