Reputation: 11
I am working on a wages application. The application should allow the user to transfer an amount from an account (the account being text file "shop" which contains the value 1000).
The user should be able to make as many transfers as they wish without overdrawing the account. Each transaction should also be recorded by a timestamp in a separate file and this is the bit I am struggling with.
Currently with the code I am using the timestamp is created fine in the file "time" except 1040ED48 appears before the time. Does anyone know why this is? Also every time I do a transaction the "time" file gets overwritten with the new timestamp. Is there a way to put each timestamp on a different line in the file in order to stop it from being completley overwritten? Sorry if this wasn't clear.
#include <limits>
#include "stdafx.h"
#include <iostream>
#include <fstream>
#include <ctime>
#include <string>
int read_balance(void);
void write_balance(int balance);
using namespace std;
int _tmain(int argc, _TCHAR* argv[])
{
cout << "How much do you wish to transfer?" << endl;
int amount = 0;
if (std::cin >> amount)
{
std::cout << "Transferred Amount:" << amount << "\n";
int balance = read_balance();
if (amount <= 0)
{
std::cout << "Amount must be positive\n";
}
else if (balance < amount)
{
std::cout << "Insufficient funds\n";
}
else
{
int new_balance = balance - amount;
write_balance(new_balance);
std::cout << "New account balance: " << new_balance << std::endl;
fstream infile;
infile.open("time.txt");
std::time_t result = std::time(nullptr);
std::string timeresult = std::ctime(&result);
infile << std::cout << timeresult << std::endl;
}
}
system("pause");
return 0;
}
int read_balance(void)
{
std::ifstream f;
f.exceptions(std::ios::failbit | std::ios::badbit);
f.open("shop.txt");
int balance;
f >> balance;
f.close();
return balance;
}
void write_balance(int balance)
{
std::ofstream f;
f.exceptions(std::ios::failbit | std::ios::badbit);
f.open("shop.txt");
f << balance;
f.close();
}
Upvotes: 0
Views: 771
Reputation: 121
One more thing. You should print the following after checking the error conditions:
std::cout << "Transferred Amount:" << amount << "\n";
int balance = read_balance();
Imagine you are at ATM. Now you try to withdraw more than what you have left in your account and ATM shows that money is transferred and indicates that you don't have enough balance.
Upvotes: 1
Reputation: 1761
If you open a file for writing, you start by deleting that file. If you don't want to delete the file, you need to open the file for appending (using app
mode.)
Upvotes: 1