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.
Related
This question already has answers here:
Why can templates only be implemented in the header file?
(17 answers)
Closed 11 months ago.
This is basically two errors in one, that seem to come from the same thing. If I define my functions in my main.cpp file, and forward declare them at the top of the file, it doesn't give me any errors and everything runs smoothly.
When trying to declutter and move things into seperate .cpp files, it starts to give me linker errors and saying things are undefined even though I am using appropriate header files. The code is shown below:
main.cpp
#include "io.h"
#include <iostream>
#include <map>
class exchangeRates;
void menu();
int main()
{
menu();
return EXIT_SUCCESS;
}
// class storing exchange rates
class exchangeRates
{
public: // Access specifier
// Data Members
std::map<std::string, double> usd = {
{"GBP", 1.2},
{"EUR", 0.7},
};
std::map<std::string, double> gbp = {
{"USD", 0.9},
{"EUR", 1.4},
};
};
// menu function
void menu()
{
// get reference currency code from user
std::string refCurrency{ obtainCodeFromUser() };
// create 'rates' instance of 'exchangeRates' class
exchangeRates rates{};
// print the exchange values for that currency
if (refCurrency == "USD")
{
printExchangeValues(rates.usd, refCurrency);
}
else if (refCurrency == "GBP")
{
printExchangeValues(rates.gbp, refCurrency);
}
else
{
std::cout << "\nInvalid currency code. Example: USD, GBP, EUR etc.\n\n";
menu();
}
}
io.h
#ifndef IO_H
#define IO_H
#include <iostream>
#include <map>
std::string obtainCodeFromUser();
double obtainAmountFromUser();
template<typename Map>
void printExchangeValues(Map& valuedCurrencies, std::string refCurrency);
#endif
io.cpp
#include "io.h"
#include <iostream>
#include <map>
// io functions for currency converter
std::string obtainCodeFromUser()
{
// obatin reference currency code from user
std::cout << "Enter currency code for reference currency (case-sensitive): ";
std::cin.clear();
std::string refCurrency{};
std::cin >> refCurrency;
std::cin.ignore(INT_MAX, '\n');
return refCurrency;
}
double obtainAmountFromUser()
{
// obtain amount of currency to be converted from user
std::cout << "Enter amount of currency to convert: ";
std::cin.clear();
double amount{};
std::cin >> amount;
std::cin.ignore(INT_MAX, '\n');
return amount;
}
template<typename Map>
void printExchangeValues(Map& valuedCurrencies, std::string refCurrency)
{
// obtain amount of currency to be converted
double amount{ obtainAmountFromUser() };
std::cout << refCurrency << " " << amount << " is worth:\n";
for (auto& item : valuedCurrencies) {
std::cout << item.first << ": " << amount * item.second << '\n';
}
}
I am still a beginner with C++ so some parts have been copied from other open-source programs, and I know there are probably plenty of places to improve my code, but I'm mainly interested in why it just won't compile. The examples I followed when learning how to use header files worked fine and I don't believe I've done anything different here.
It says the identifiers "obtainCodeFromUser" and "printExchangeValues" are undefined.
The linker error it gives is LNK2019 'unresolved external symbol ...' and it seems to be relating to the printExchangeValues function.
Any help is massively appreciated!
The issue mentioned by WhozCraig is very useful, I hope you will read it carefully. Regarding your question, after I modified some code, the program can run correctly. The error is caused by the template. Since you are a beginner and the program is not very complicated, the following code is more convenient for you to understand:
main.cpp
#include "io.h"
#include <iostream>
#include <map>
// class storing exchange rates
class exchangeRates
{
public: // Access specifier
// Data Members
std::map<std::string, double> usd = {
{"GBP", 1.2},
{"EUR", 0.7},
};
std::map<std::string, double> gbp = {
{"USD", 0.9},
{"EUR", 1.4},
};
};
template<typename Map>
void printExchangeValues(Map& valuedCurrencies, std::string refCurrency)
{
// obtain amount of currency to be converted
double amount{ obtainAmountFromUser() };
std::cout << refCurrency << " " << amount << " is worth:\n";
for (auto& item : valuedCurrencies) {
std::cout << item.first << ": " << amount * item.second << '\n';
}
}
// menu function
void menu()
{
// get reference currency code from user
std::string refCurrency{ obtainCodeFromUser() };
// create 'rates' instance of 'exchangeRates' class
exchangeRates rates{};
// print the exchange values for that currency
if (refCurrency == "USD")
{
printExchangeValues(rates.usd, refCurrency);
}
else if (refCurrency == "GBP")
{
printExchangeValues(rates.gbp, refCurrency);
}
else
{
std::cout << "\nInvalid currency code. Example: USD, GBP, EUR etc.\n\n";
menu();
}
}
int main()
{
menu();
return EXIT_SUCCESS;
}
io.h
#ifndef IO_H
#define IO_H
#include <iostream>
#include <map>
std::string obtainCodeFromUser();
double obtainAmountFromUser();
#endif
io.cpp
#include "io.h"
#include <iostream>
#include <map>
// io functions for currency converter
std::string obtainCodeFromUser()
{
// obatin reference currency code from user
std::cout << "Enter currency code for reference currency (case-sensitive): ";
std::cin.clear();
std::string refCurrency{};
std::cin >> refCurrency;
std::cin.ignore(INT_MAX, '\n');
return refCurrency;
}
double obtainAmountFromUser()
{
// obtain amount of currency to be converted from user
std::cout << "Enter amount of currency to convert: ";
std::cin.clear();
double amount{};
std::cin >> amount;
std::cin.ignore(INT_MAX, '\n');
return amount;
}
I am working on some code to make a wallet to hold different currencies and this is my first time programming in c++ as a c programmer. Every time I make a new currency I want to add it to the list of valid Currencies that my wallet will be able to hold. To do this I make a currency class with a list that I want to add to every time a new currency is spawned. The error I get is error: no matching function for call to ‘std::__cxx11::list<Currency>::push_back(Currency*) CurrencyList.push_back(this);"\
Currency.h looks like:
#ifndef CURRENCY_H
#define CURRENCY_H
#include <string>
#include <list>
class Currency {
public:
//Instances of class
int id;
float max;
float left_over;
std::string coinName;
//Methods
float buyFrom(float amount);
float sellBack(float amount);
//constructor
Currency();
};
extern std::list<Currency> CurrencyList; //global list
#endif
Currency.c looks like
#include "currency.h"
#include <iostream>
Currency::Currency() {
Currency::id = 0;
std::cout << "Input name :" << std::endl;
std::cin >> Currency::coinName;
std::cout << "Input max :" << std::endl;
std::cin >> Currency::max;
Currency::left_over = Currency::max - 0;
CurrencyList.push_back(this);
}
float Currency::buyFrom(float amount) {
Currency::left_over-=amount;
std::cout << "Currency just lost :" << amount << "remaining is : " << Currency::left_over << std::endl;
}
float Currency::sellBack(float amount) {
Currency::left_over -= amount;
std::cout << "Currency just gained : " << amount << " remaining is : " << Currency::left_over << std::endl;;
}
The main is quiet simple it is only meant to spawn an object to test, that looks something like this.
Main.cpp
#include <iostream>
#include "wallet.h"
#include "currency.h"
int main(){
std::cout << "Hello World" << std::endl;
Currency currencyTest;
currencyTest.buyFrom(200.3);
}
Note that this is a pointer, but your list holds actual objects, not pointers.
So just dereference the pointer and you should be fine:
CurrencyList.push_back(*this);
I have been trying to get the current date in C++ for a while now and I cannot figure out what I am doing wrong. I have looked at several sites and all of the solutions that I implement I get an error that says, “This function or variable may be unsafe. Consider using localtime_s instead.” I tried several of the solutions found here (including the one below) but I could not get any of them to work. What am I doing wrong?
#include <iostream>
#include <iomanip>
#include <string>
#include <ctime>
using namespace std;
int main()
{
const int SALARY = 18;
const int COMMISSION = .08;
const int BONUS = .03;
int monthlySales;
int appointmentNumber;
time_t t = time(0); // get time now
struct tm * now = localtime(&t);
string name;
//this is where the user adds their name and date
cout << "Please enter the sales representative's name: ";
cin >> name;
cout << "Please enter the number of appointments: ";
cin >> appointmentNumber;
cout << "Please enter the amount of sales for the month: $";
cin >> monthlySales;
//clear screen and execute code
system("cls");
cout << setfill(' ');
cout << "Sales Representative:" << name << endl;
cout << "Pay Date:" << (now->tm_mon + 1) << " " << now->tm_mday << " " << (now->tm_year + 1900) << endl;
cout << "Work Count:" << appointmentNumber << "Sale Amount"
<< monthlySales << endl;
system("pause");
return 0;
}
You can try below code and description beneath it.
#include <iostream>
#include <ctime>
int main ()
{
time_t rawtime;
struct tm * timeinfo;
char buffer[80];
time (&rawtime);
timeinfo = localtime(&rawtime);
strftime(buffer,80,"%d-%m-%Y %I:%M:%S",timeinfo);
std::string str(buffer);
std::cout << str;
return 0;
}
Function
time_t time (time_t* timer);
function returns this value, and if the argument is not a null pointer, it also sets this value to the object pointed by timer.
Parameters
timer
Pointer to an object of type time_t, where the time value is stored.you can also pass it null pointer in case not required
Return Value
The current calendar time as a time_t object.If the function could not retrieve the calendar time, it returns a value of -1.
Here is how I do it:
#include "date/tz.h"
#include <iostream>
int
main()
{
using namespace std::chrono;
std::cout << date::make_zoned(date::current_zone(), system_clock::now()) << '\n';
}
which just output for me:
2016-10-18 10:39:10.526768 EDT
I use this C++11/14 portable, free, open-source library. It is thread-safe. It is based on <chrono>. It is type safe and easy to use. If you need more functionality, this library will do it.
Get the local time in another timezone
Convert local time directly from one timezone to another.
Take leap seconds into account in time computations.
Stream out / stream in time stamps round trip with any precision, and no loss of information.
Search all timezones for a property (such as abbreviation or offset).
This library is being proposed to the C++ standards committee, draft here.
You're getting this warning perhaps because localtime() is not thread-safe. Two instances calling this function might result in some discrepancy.
[...] localtime returns a pointer to a static buffer (std::tm*).
Another thread can call the function and the static buffer could be
overwritten before the first thread has finished reading the content
of the struct std::tm*.
The standard and cross-platform way is to use chrono.
#include <iostream>
#include <chrono>
int main(){
std::time_t now_time = std::chrono::system_clock::to_time_t(std::chrono::system_clock::now());
std::cout << "Now:" << std::ctime(&now_time);
}
This is another way that could work:
time_t current_time;
struct tm *timeinfo;
time(¤t_time);
timeinfo = localtime(¤t_time);
string date = asctime(timeinfo);
I greatly appreciate all of your timely the responses. Ultimately I was able to use a variation of Heemanshu Bhalla’s response. I added ‘_CRT_SECURE_NO_WARNINGS’ to the preprocessor definitions by going here then I altered Heemanshu’s code to the following code. This suited my needs.
#include <iostream>
#include <ctime>
#include <string>
using namespace std;
int main()
{
time_t rawtime;
struct tm * timeinfo;
char buffer[80];
time(&rawtime);
timeinfo = localtime(&rawtime);
strftime(buffer, 80, "%m/%d/%Y ", timeinfo);
string str(buffer);
cout << str << endl;
system("PAUSE");
return 0;
}
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.
I am still new to c++ and just started to learn about classes and OOP. I have been practicing trying to make classes out of any item I can think of, so I made a phone class. Code is below. The problem is no matter what number I give it, it displays the same WRONG number everytime. The crazy thing is in the beginning I had given the phone class a variable to store its own number and gave the class instance its own number. That number is the number it keeps wanting to "call". Even after going back several times and making sure I wasn't calling the wring variable I completely deleted the variable and the code still displays the same number. The number is 214-748-3647. Makes me feel like my computer is haunted. Could anyone help?
CODE DOESN'T ACTUALLY MAKE ANY SORT OF PHONE CALL OR ANY CONNECTION WHAT SO EVER
PHONE CLASS HEADER
#ifndef PHONE_H_INCLUDED
#define PHONE_H_INCLUDED
#include <string>
using namespace std;
class Phone{
public:
string Brand;
int Serial;
string CellId;
void Call();
private:
void Dial(int NumberToDial);
void EndCall();
};
#endif // PHONE_H_INCLUDED
PHONE SOURCE CODE
#include <iostream>
#include <string>
#include <sstream>
#include "phone.h"
using namespace std;
void Phone::Call(){
string UserInput = "0";
int NumberToCall = 0;
cout << "What number would you like to call?" << endl << endl;
getline(cin, UserInput);
if(UserInput.length() != 10){
cout << endl << "invalid digits" << endl;
Call();
}
else{
stringstream(UserInput) >> NumberToCall;
Dial(NumberToCall);
}
}
void Phone::Dial(int NumberToDial = 0){
ostringstream converter;
string Number;
converter << NumberToDial;
Number = converter.str();
cout << "Dialing ";
for(int i=0;i<10;i++){
cout << Number[i];
if(i==2){
cout << "-";
}
if(i==5){
cout << "-";
}
}
cout << endl << endl << "Press any key to end the call..." << endl << endl;
cin.get();
EndCall();
}
void Phone::EndCall(){
cout << "Call ended." << endl << endl;
}
Aaaaannnnd my MAIN
#include <iostream>
#include <cstdlib>
#include "phone.h"
using namespace std;
int main()
{
Phone MyPhone;
MyPhone.Brand = "iPhone 5";
MyPhone.CellId = "F2D9G3A2";
MyPhone.Serial = 1411512;
MyPhone.Call();
return 0;
}
This is a very simple answer. You're code and logic is fine. The error occurs because you convert the std::string which holds the phone number to an integer. This is a problem because a typical 10 digit phone number is too big to fit inside the int type. Have a look here to see the min and max numbers you can fit in different types: http://www.cplusplus.com/reference/climits/
Look at this line here actually.
Maximum value for an object of type long int: 2147483647 (231-1) or greater
Funny how the max value is that mysterious phone number.