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();
}
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.)
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.
Related
Okay so I have a programming project due in about 7 minutes. My project reads a double GPA and a string Name in a txt file. I correctly place the GPA and Names into separate STL lists for the project. My problem comes when I try to push the highest GPA value into a queue. At that point it gives the error that no instance of overloaded function.
Since I am using pointers, I have tried different methods of using pointers but to no avail. I figure that pointers might be a part of the problem.
#include <iostream>
#include <iomanip>
#include <fstream>
#include <string>
#include <list>
#include <queue>
using namespace std;
//using std::because it says cout is ambiguous even with std included
int main()
{
double GPA;
double highestGPA;
string name;
list<double> listGPA; //lists and their iterators
//list<double>::iterator ptrGPA, ptrHighestGPA;
double *ptrGPA, *ptrHighestGPA;
list<string> listName;
//list<string>::iterator ptrName, ptrHighestName;
string *ptrName, *ptrHighestName;
queue<double> queueGPA; //queues
//queueGPA.front() = 0;
queue<string> queueName;
//queueName.front() = "";
ifstream infile;
infile.open("HighestGPAData.txt");
if (!infile) //if file doenst exist
{
std::cout << "The input file does not "
<< "exist. Program terminates!"
<< endl;
std::system("pause");
return 1;
}
std::cout << fixed << showpoint;
std::cout << setprecision(2);
infile >> GPA >> name;
while (infile) { //place contents of file into 2 STL lists
listGPA.push_back(GPA);
listName.push_back(name);
infile >> GPA >> name;
}
std::cout << "\nSTL list for GPA:\n";
for (auto g : listGPA) { //range based for loop that prints GPA list
std::cout << g << "\n";
}
std::cout << "\nSTL list for names:\n";
for (auto s : listName) { //range based for loop that prints name
std::cout << s << "\n";
}
std::system("pause");
ptrGPA = &listGPA.front(); //initialize pointers for each list
ptrHighestGPA = ptrGPA;
ptrName = &listName.front();
ptrHighestName = ptrName;
while (!listGPA.empty()) // there are two lists (name and GPA)
if (ptrGPA > ptrHighestGPA) {
while (!queueGPA.empty()) { //destroy queue i (so a lower
queueGPA.pop();
}
while (!queueName.empty()) { //destroy queue if a higher //gpa is found (so a lower gpa is not printed)
queueName.pop();
}
/***********************problem here */
ptrHighestGPA = ptrGPA;
queueGPA.push(ptrHighestGPA); //add to queue if it is
ptrHighestName = ptrName;
queueName.push(ptrHighestName);
}
else if (ptrGPA == ptrHighestGPA) { //add to the queue ifcurrent gpa
queueGPA.push(ptrHighestGPA);
queueName.push(ptrHighestName);
}
/* end problem */
listGPA.pop_front();
listName.pop_front();
ptrGPA++;
ptrName++; //= listName.front();
}
while (!queueGPA.empty()) { //print the largest gpa.
std::cout << queueGPA.front() << " ";
queueGPA.pop();
}
std::cout << "\n";
while (!queueName.empty()) { //print who has the highest gpa
std::cout << queueName.front() << " ";
queueName.pop();
}
std::system("pause");
return 0;
}
Currently it outputs both lists but I can easily comment that out. I want the queues queueName and queueGPA to contain the highest GPA and name associated with that GPA from the lists listGPA and listName.
Thank you guys
i have that c++ project. i want to get today's date to compare it with a saved date in my files. i already searched but all i found is i can output it on the console but that isn't what i want. is it possible?
#include <iostream>
#include <cmath>
#include <string>
#include <chrono>
#include <ctime>
using namespace std;
static double interset = .05;
class Account{
public:
string ID;
double Balance;
void Deposit(double bal){
Balance += bal;
}
void Withdraw(double bal){
if (bal > Balance){
cout << "Please check the entered amount" << endl;
}
else{
Balance -= bal;
}
}
void BalanceInqu(){
cout << "Your Current Balance Is\t" << Balance << endl;
}
};
class SavingAccount : public Account{
public:
void intersetRate(){
\\i want to put here a function that calculates the interest rate of an client depending on his account creation date
}
};
Edit: i want to get the date to store it into variable and compare it with other dates
If you have the date or time for now, you just need to subtract the start time and the transform the result into days, if that's not already the case. So this means that you don't need to get the actual date for today.
The time_since_epoch can be enough, because you just want to have the difference between 2 timestamps.
#include <iostream>
#include <chrono>
#include <ctime>
tm chronoTPtoTM(const std::chrono::system_clock::time_point& tp) {
time_t aux = std::chrono::system_clock::to_time_t(tp);
return *localtime(&aux);
}
int main(int argc, char** argv) {
std::chrono::system_clock::time_point t = std::chrono::system_clock::now();
tm local_time = chronoTPtoTM(t);
std::cout << "Now is "
<< local_time.tm_year+1900 << "/"
<< local_time.tm_mon+1 << "/"
<< local_time.tm_mday << " "
<< local_time.tm_hour << "h"
<< local_time.tm_min << "m"
<< local_time.tm_sec << "s"
<< std::endl;
return 0;
}
This is a simple working example of the usage of the std::chrono::system_clock::time_point. This class even has comparator operators defined so you can compare two of these easily with <, >, <=, >=, "==" and "!=".
In the example, I've included a way to convert the time_point into a human readable format.
First of all, Thank you for the help and I hope I'm following your guidelines correctly, if I'm not, I'd be more than happy to correct it.
I need some help with an assignment I have. After finally getting it to run, my program won't open the files I need. The program should open a file named prog10in.txt and output it into a file named prog10out.txt However, I put a line in it that would tell me if it failed and that keeps coming up. I am doing this in Visual Studio. I need to understand how to properly open the file whether my error is in the code or in Visual Studio. The program compiles without error.
The error should be in getAccountInfo() or outputFile().
Source.cpp:
#include <iostream>
#include <string>
#include "Account.h"
#include "Bank.h"
#include <cstdio>
#include <fstream>
#include <iomanip>
using namespace std;
ifstream inStream;
int main(int argc, char* argv[])
{
Account accounts[MAXIMUM_ACCOUNTS];
Bank Customer;
int AccountNumber = 0;
int ID;
string lastName;
string firstName;
double balance;
Customer.getAccountInfo(argv, AccountNumber, ID, lastName, firstName,balance, accounts);
Customer.sort(AccountNumber, accounts);
Customer.outputFile(argv, AccountNumber, accounts);
}
There is an Account.h and Account.cpp file that holds the account information class.
Bank.cpp:
#include <iostream>
#include <string>
#include "Account.h"
#include "Bank.h"
#include <cstdio>
#include <fstream>
#include <iomanip>
void Bank::getAccountInfo(char* argv[], int& accountNumber, int& accountID, std::string& accountLastName, std::string& accountFirstName, double& accountBalance, Account Customers[MAXIMUM_ACCOUNTS])
{
std::ifstream fin;
int accountIndex = 0;
fin.open(argv[1]);
if (fin.fail())
{
std::cout << "Input file did not open" << std::endl;
system("pause");
exit(1);
}
while (!fin.eof() && accountIndex < MAXIMUM_ACCOUNTS)
{
std::cout.setf(std::ios::fixed | std::ios::showpoint | std::ios::right);
std::cout.precision(2);
fin >> accountID >> accountLastName >> accountFirstName >> accountBalance;
fin.ignore(1, ' ');
Customers[accountIndex]._accountID = accountID;
Customers[accountIndex]._accountLastName = accountLastName;
Customers[accountIndex]._accountFirstName = accountFirstName;
Customers[accountIndex]._accountBalance = accountBalance;
accountIndex++;
accountNumber++;
}
std::cout << "Clients: " << accountIndex << std::endl;
}
void Bank::sort(int accountNumber, Account Customers[MAXIMUM_ACCOUNTS])
{
int nextSmallest;
int IDtemp;
std::string lastNameTemp;
std::string firstNameTemp;
double balanceTemp;
for (int accountIndex = 0; accountIndex < accountNumber; accountIndex++)
{
nextSmallest = accountIndex;
for (int accountIndex2 = accountIndex + 1; accountIndex2 < accountNumber; accountIndex2++)
{
if (Customers[accountIndex2]._accountID < Customers[nextSmallest]._accountID)
{
nextSmallest = accountIndex2;
}
IDtemp = Customers[accountIndex]._accountID;
Customers[accountIndex]._accountID = Customers[nextSmallest]._accountID;
Customers[nextSmallest]._accountID = IDtemp;
lastNameTemp = Customers[accountIndex]._accountLastName;
Customers[accountIndex]._accountLastName = Customers[nextSmallest]._accountLastName;
Customers[nextSmallest]._accountLastName = lastNameTemp;
firstNameTemp = Customers[accountIndex]._accountFirstName;
Customers[accountIndex]._accountFirstName = Customers[nextSmallest]._accountFirstName;
Customers[nextSmallest]._accountFirstName = firstNameTemp;
balanceTemp = Customers[accountIndex]._accountBalance;
Customers[accountIndex]._accountBalance = Customers[nextSmallest]._accountBalance;
Customers[nextSmallest]._accountBalance = balanceTemp;
}
}
}
void Bank::outputFile(char* argv[], int accountNumber, Account Customers[MAXIMUM_ACCOUNTS])
{
int outFileIndex;
std::ofstream fout;
fout.open(argv[2]);
if (fout.fail())
{
std::cout << "Output file did not open" << std::endl;
system("pause");
exit(1);
}
if (fout.fail())
{
std::cout << "Output failed" << std::endl;
exit(0);
}
fout.setf(std::ios::fixed | std::ios::showpoint | std::ios::right);
fout.precision(2);
for (outFileIndex = 0; outFileIndex < accountNumber; outFileIndex++)
{
fout << std::setw(6) << Customers[outFileIndex]._accountID;
fout << std::setw(10) << Customers[outFileIndex]._accountLastName;
fout << std::setw(10) << Customers[outFileIndex]._accountFirstName;
fout << std::setw(10) << Customers[outFileIndex]._accountBalance;
fout << std::setw(10) << std::endl;
}
}
Again, thank you guys for the help.
I think your program don't find the input file. right? because the output file will be created if not exists.
So about the input, if you use an absolute path it should work unless the path is wrong. but if you are using a relative path. you should know that running the program from visual studio the current directory (.) will be the projects directory.
Your path is not correct. if filename is "abc.txt" and the file is present in same folder as that of binary (exe file) than you only need to provide the name. If not than provide the full path of the file in double quotes (if space is present)
I have a project for a class and I'm not sure what type of array I should be using for this program. I have to make a stock market program where the user buys, sells and views stock listings and checks their account balance. There are two text files that contain the following data:
Leon1111 5000.00
Wise2222 10000.00
Woo3333 3000.00
White4444 7000.00
Head5555 4000.00
and
Apple AAPL 450.00
Boeing BA 75.50
Intel INTC 22.30
Rambus RMBS 5.55
Sirius SIRI 3.15
Skyworks SWKS 25.35
Xilinx XLNX 36.80
This is the code I've written so far:
#include <iostream>
#include <fstream>
#include <cstdlib>
#include <iomanip>
#include <string>
using namespace std;
int main()
{
ofstream outStream;
int option;
do
{
cout << "1) Check Stock Listings " << endl;
cout << "2) Buy Stock " << endl;
cout << "3) Sell Stock" << endl;
cout << "4) Check Account Balance " << endl;
cout << "5) Quit " << endl << endl;
cout << "Please select an option : ";
cin >> option;
cout << endl;
if (option == 1)
{
fstream CompaniesFile;
CompaniesFile.open("Companies.txt");
if (CompaniesFile.is_open())
{
string s;
while (getline(CompaniesFile, s, '\n'))
{
cout << s << endl;
}
}
CompaniesFile.close();
}
else if (option == 2)
{
}
else if (option == 3)
{
}
else if (option == 4)
{
fstream AccountFile;
AccountFile.open("Account.txt");
if (AccountFile.is_open())
{
string t;
while (getline(AccountFile, t))
{
cout << t << endl;
}
}
AccountFile.close();
}
else if (option == 5)
{
cout << "Program Terminated. Have a nice day!" << endl << endl;
}
else
{
cout << "Invalid Option entered" << endl;
}
}
while (option != 5);
return 0;
}
class cCompany
{
std::string myName;
std::string mySymbol;
double myPrice;
public:
cCompany( const std::string& name,
const std::string& symbol,
double price )
: myName( name ), mySymbol( symbol ), myPrice( price )
{}
};
std::vector< cCompany > vCompany;
class cAccount
{
std::string myName
double myBalance;
public:
cAccount( const std:string& name, double balance )
: myName( name ), myBalance( balance )
{}
};
std:vector< cAccount > vAccount;
...
std::string name;
std::string symbol;
double price;
while ( CompaniesFile.good() )
{
CompaniesFile >> name;
CompaniesFile >> symbol;
CompaniesFile >> price;
vCompany.push_back( cCompany( name, symbol, price ));
}
You are going to probably need a bit more than name and balance for an account holder, so if I had my druthers I would use a vector (or map) of a class for account holders. The account holder class would hold name, balance, and then a vector (or even better a map) of shares that the person holds and the number of shares. Something like:
class AccountHolder{
private:
std::string name_;
long long int balance_; //balance in cents
//to allow for something like buy("AAPL", 100);
// to be implemented as:
// void buy(std::string symbol, long int shares)
// {
// long int price = shares * sharePrice[symbol];
// if (balance_ >= price)
// {
// balance_ -= price;
// holdings_[symbol] += shares;
// } else
// throw(INSUFFICIENT_FUNDS);
// }
std::map<std::string, long long int> holdings_;
public:
...
};
For shares, I would use a map since you only need to know their name (and/or symbol) and the price. Maybe you can have the key be the symbol, and then the value to be price, and another map for symbol and full name. This way you can easily find the share prices: all you need to do is
std::cout << "price of a single share from " << fullName["AAPL"]
<< " is: " << sharePrice["AAPL"] << "\n";
Try to make your application more OO-like (Object Oriented). My suggestion is first you can create some data structures:
struct user { string name; double balance; }
struct stock { string name; double price; }
struct stockBought { string userName; string stockName; int share; }
then use something to save your data, for example,
list<user> users;
list<stock> stocks;
list<stockBought> stockBought;
then you should have a function to read from the two files
readUsersFromFile(users, fUsersFile);
readStocksFromFile(stocks, fStockFile);
then you should have a function to update the list
update(users, 3, 1, 4000.0); //update the users list: 3rd user, 1st column (5000.0 => 4000.0)
add(stockBought, "Leon1111", "AAPL", 1); //leon bought 1 share of AAPL
then you have to implement all the functions needed for the 5 options. Add more utility functions/classes as you move on.
Once you finish the 1st version. you can polish your code to make it run faster (adding index etc) or look better (better class).
How do you create multiple new class objects using the default class constructor?
For a project I am having to write a program that writes three class objects into a file. That I have done... The next part is being able to read the data back into three separate class objects using a readData function and then displaying the data. I am completely lost at how to do this so I don't have any code in the readData function.
Here is an example of what the object looks like when it is being written to the file.
employee name(21, "first last", "45 East State", "661-9000", 30, 12.00);
Here is the bulk of my code the employee class is fairly basic but here is the default class constructor.
employee::employee ();
employee::employee(int locEmpNumber, string locName, string locaddress, string locphone, double locHrWorked, double locHrWage)
#include "employee.h"
#include <string>
#include <iomanip>
#include <iostream>
#include <fstream>
using namespace std;
void writeData (const employee& e);
void readData (const employee& e);
void printCheck (const employee& e);
int main( )
{
//Declarations
const int ONE = 1;
const int TWO = 2;
int userInput;
cout << "This program has two options:" << endl;
cout << "1 - Create a data files called 'EmployeeInfo.txt', or" << endl;
cout << "2 - Read data from a file and print paychecks." << endl;
cout << "Please enter (1) to create a file or (2) to print checks: ";
cin >> userInput;
if (userInput == ONE)
{
//Create employee objects:
employee joe(37, "Joe Brown", "123 Main St.", "123-6788", 45, 10.00);
employee sam(21, "Sam Jones", "45 East State", "661-9000", 30, 12.00);
employee mary(15, "Mary Smith", "12 High Street", "401-8900", 40, 15.00);
ofstream empFile ("EmployeeInfo.txt");
//Employee objects to write themselves out to the file.
writeData(joe);
writeData(sam);
writeData(mary);
//Close the file.
empFile.close();
//Print an message that creation of the file is complete.
system("CLS");
cout << "\nCreation of 'EmployeeInfo.txt' has completed.\n";
cout << "\nYou can now run option 2.\n";
//Exit.
system("PAUSE");
return 0;
}
else if (userInput == TWO)
{
//Create three new Employee objects, using the default Employee constructor.
//Open the file that you just saved.
//Have each object read itself in from the file.
//Call the printCheck( ) function for each of the three new objects, just as you did in the previous project.
}
else
{
system("CLS");
cout << "Incorrect entry.... Please try again and follow directions closely! \n" << endl;
system("PAUSE");
return 0;
}
}
void writeData(const employee& e)
{
fstream empFile;
empFile.open ("EmployeeInfo.txt", ios::app);
empFile << e.getEmpNumber() << "\n";
empFile << e.getName() << "\n";
empFile << e.getAddress() << "\n";
empFile << e.getPhone() << "\n";
empFile << e.getHrWorked() << "\n";
empFile << e.getHrWage() << "\n";
}
void readData(const employee& e)
{
fstream empFile;
empFile.open ("EmployeeInfo.txt", ios::in);
if(empFile.fail())
{
cout << "File could not be open. Please try option 1 then option 2.\n" << endl;
return;
}
}
It's good to see that you have made an effort at solving the problem. However, there is a mismatch between what you set out in your question and some of the comments in your code. It seems clear to me that a key part of your brief is that the employee object itself is required to be able to write itself to the file and to read itself back from the file.
You have written code that will write the contents of the object to the file rather than having the object write itself to the file. It might seem like I'm splitting hairs on this one, but this is the essence of what Object Oriented Programming is about. Encapsulating the functionality within the object itself is the real goal here.
I've included some code below to help you. Hopefully this will make good sense for you.
class employee
{
private:
int _locEmpNumber;
std::string _locName;
std::string _locAddress;
std::string _locPhone;
double _locHrWorked;
double _locHrWage;
public:
employee();
employee(int locEmpNumber, std::string locName, std::string locAddress, std::string locPhone, double locHrWorked, double locHrWage);
//object should be able to save itself as per your project brief.
void writeData(std::ofstream &empFile);
//object should be able to read itself from file as per your project brief
void readData(std::ifstream &empFile);
};
employee::employee()
{
_locEmpNumber = 0;
_locHrWorked = _locHrWage = 0;
}
employee::employee(int locEmpNumber, std::string locName, std::string locAddress, std::string locPhone, double locHrWorked, double locHrWage)
{
_locEmpNumber = locEmpNumber;
_locName = locName;
_locAddress = locAddress;
_locPhone = locPhone;
_locHrWorked = locHrWorked;
_locHrWage = locHrWage;
}
//
//From what I can glean from your brief ...
//Employee objects to write themselves out to the file!!!
void employee::writeData(std::ofstream &empFile)
{
empFile << _locEmpNumber << std::endl;
empFile << _locName << std::endl;
empFile << _locAddress<< std::endl;
empFile << _locPhone << std::endl;
empFile << _locHrWorked << std::endl;
empFile << _locHrWage << std::endl;
}
//
//Again, from what I can glean from your brief ...
//Have each object read itself in from the file!!!
void employee::readData(std::ifstream &empFile)
{
//Normally you would have error handling in a method like this and
//would either return a response that indicates that the operation
//succeded or failed. You might alternatively use exception handling
//or indeed a combination of both.
//
//Normally you would reset all members to initial / empty values before
//reading values into them from your file. In this case we will omit that
//for the purposes of simplicity. The main reason you would reset members
//is to ensure that when reusing an object you don't end up with partial
//data from the current "read" operation mixed with partial data that
//was already in the object before you started reading.
std::string inputStr;
std::getline(empFile, inputStr);
_locEmpNumber = atoi(inputStr.c_str());
std::getline(empFile, _locName);
std::getline(empFile, _locAddress);
std::getline(empFile, _locPhone);
std::getline(empFile, inputStr);
_locHrWorked = atof(inputStr.c_str());
std::getline(empFile, inputStr);
_locHrWage = atof(inputStr.c_str());
}
int main(int argc, char* argv[])
{
//Declarations
const int ONE = 1;
const int TWO = 2;
int userInput;
std::cout << "This program has two options:" << std::endl;
std::cout << "1 - Create a data files called 'EmployeeInfo.txt', or" << std::endl;
std::cout << "2 - Read data from a file and print paychecks." << std::endl;
std::cout << "Please enter (1) to create a file or (2) to print checks: ";
std::cin >> userInput;
if (userInput == ONE)
{
//Create employee objects:
employee joe(37, "Joe Brown", "123 Main St.", "123-6788", 45, 10.00);
employee sam(21, "Sam Jones", "45 East State", "661-9000", 30, 12.00);
employee mary(15, "Mary Smith", "12 High Street", "401-8900", 40, 15.00);
std::ofstream empFile ("EmployeeInfo.txt");
//Employee objects to write themselves out to the file.
joe.writeData(empFile);
sam.writeData(empFile);
mary.writeData(empFile);
// writeData(joe);
// writeData(sam);
// writeData(mary);
//Close the file.
empFile.close();
//Print an message that creation of the file is complete.
system("CLS");
std::cout << "\nCreation of 'EmployeeInfo.txt' has completed.\n";
std::cout << "\nYou can now run option 2.\n";
//Exit.
system("PAUSE");
return 0;
}
else if (userInput == TWO)
{
//Create three new Employee objects, using the default Employee constructor.
employee joe;
employee sam;
employee mary;
//Open the file that you just saved.
std::ifstream empFile("EmployeeInfo.txt");
//Have each object read itself in from the file.
joe.readData(empFile);
sam.readData(empFile);
mary.readData(empFile);
empFile.close();
//Call the printCheck( ) function for each of the three new objects, just as you did in the previous project.
//I'll leave it to you to add this yourself.
}
else
{
system("CLS");
std::cout << "Incorrect entry.... Please try again and follow directions closely! \n" << std::endl;
system("PAUSE");
return 0;
}
return 0;
}