Group
File Management in C++
Objective
1. Create a program that simulates a simple ATM with options to deposit or withdraw money.
2. For each operation, write a log entry into a file called "atm_log.txt".
3. Each log entry should include the operation type, the amount, and a timestamp.
4. Use conditionals to ensure the balance does not go negative during withdrawal.
5. Display the current balance after each operation.
Develop a program that logs ATM operations into a log file.
Example C++ Exercise
Show C++ Code
#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
}
Output
//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