Hello I am new to C++ expecialy dates in C++.. how can I compare these numbers 29(day) 08(month) 86(year) with todays date to get age ?
Here is hwo I started my function:
std::string CodeP, day, month, year, age;
std::cout<<"Enter Permanent Code(example: SALA86082914) :\n "; //birthday first six numbers in code
std::cin>>CodeP;
year = CodeP.substr (4,2);
month = CodeP.substr (6,2);
day = CodeP.substr (8,2);
std::cout<<"day :"<<day <<'\n';
std::cout<<"month :"<<month <<'\n';
std::cout<<"year :"<<year <<'\n';
//then get today's date to compare with the numbers of birthday to get age
First subtract the years to get the difference. Now compare the months; if today's month is greater than the birth month, you're done. If not, compare the days; if today's day is greater than the birth day, you're done. Otherwise subtract one from the difference and that's the age.
Try my code below, I already did the necessary code for the comparing and the processing of two dates that you will be needing. Take note that my code's role is just to compare two dates and give the resulting age based from those dates.
Sorry but I have to leave you the job of creating a code that will give you your expected output based from a six-digit birthday input. I guess you already know that you still have to come up with your own solution for your problem, we are only here to give you an idea on how you can tackle it. We could only do so much to help and support you. Hope my post was helpful!
class age
{
private:
int day;
int month;
int year;
public:
age():day(1), month(1), year(1)
{}
void get()
{
cout<<endl;
cout<<"enter the day(dd):";
cin>>day;
cout<<"enter the month(mm):";
cin>>month;
cout<<"enter the year(yyyy):";
cin>>year;
cout<<endl;
}
void print(age a1, age a2)
{
if(a1.day>a2.day && a1.month>a2.month)
{
cout<<"your age is DD-MM-YYYY"<<endl;
cout<<"\t\t"<<a1.day-a2.day<<"-"<<a1.month-a2.month<<"-"<<a1.year-a2.year;
cout<<endl<<endl;
}
else if(a1.day<a2.day && a1.month>a2.month)
{
cout<<"your age is DD-MM-YYYY"<<endl;
cout<<"\t\t"<<(a1.day+30)-a2.day<<"-"<<(a1.month-1)-a2.month<<"-"<<a1.year-a2.year;?
cout<<endl<<endl;
}
else if(a1.day>a2.day && a1.month<a2.month)
{
cout<<"your age is DD-MM-YYYY"<<endl;
cout<<"\t\t"<<a1.day-a2.day<<"-"<<(a1.month+12)-a2.month<<"-"<<(a1.year-1)-a2.year;
cout<<endl<<endl;
}
else if(a1.day<a2.day && a1.month<a2.month)
{
cout<<"your age is DD-MM-YYYY"<<endl;
cout<<"\t\t"<<(a1.day+30)-a2.day<<"-"<<(a1.month+11)-a2.month<<"-"<<(a1.year-1)-a2.year;
cout<<endl<<endl;
}
}
};
int main()
{
age a1, a2, a3;
cout<<"\t Enter the current date.";
cout<<endl<<endl;
a1.get();
cout<<"\t enter Date of Birth.";
cout<<endl<<endl;
a2.get();
a3.print(a1,a2);
return 0;
}
this will calculate an aproximate of the age(years):
#include <ctime>
#include <iostream>
using namespace std;
int main(){
struct tm date = {0};
int day, month, year;
cout<<"Year: ";
cin>>year;
cout<<"Month: ";
cin>>month;
cout<<"Day: ";
cin>>day;
date.tm_year = year-1900;
date.tm_mon = month-1;
date.tm_mday = day;
time_t normal = mktime(&date);
time_t current;
time(¤t);
long d = (difftime(current, normal) + 86400L/2) / 86400L;
cout<<"You have~: "<<d/365.0<<" years.\n";
return (0);
}
The best way to do that is using Boost.Gregorian:
Assuming
#include <boost/date_time/gregorian/gregorian.hpp>
using namespace boost::gregorian;
You would do:
date bday { from_undelimited_string(std::string("19")+a.substr(4,6)) };
date now = day_clock::local_day();
unsigned years = 0;
year_iterator y { bday };
while( *++y <= *year_iterator(now) )
++years;
--y;
std::cout << *y << "\n";
unsigned months = 0;
month_iterator m { *y };
while( *++m <= *month_iterator(now) )
++months;
--m;
std::cout << *m << "\n";
unsigned days = 0;
day_iterator d { *m };
while( *++d <= *day_iterator(now) )
++days;
--d;
std::cout << *d << "\n";
std::cout << years << " years, " << months << " months, " << days << " days\n";
I found another (simpler?) answer, using Boost.Gregorian
#include <boost/date_time/gregorian/gregorian.hpp>
using namespace boost::gregorian;
template<typename Iterator, typename Date>
struct date_count : public std::pair<unsigned, Date> {
typedef std::pair<unsigned, Date> p;
operator unsigned() { return p::first; }
operator Date() { return p::second; }
date_count(Date begin, Date end) : p(0, begin) {
Iterator b { begin };
while( *++b <= end )
++p::first;
p::second = *--b;
}
};
And you just have to use it this way:
date bday { from_undelimited_string(std::string("19")+a.substr(4,6)) };
date now = day_clock::local_day();
date_count<year_iterator, date> years { bday, now };
date_count<month_iterator, date> months { years, now };
date_count<day_iterator, date> days { months, now };
std::cout << "From " << bday << " to " << now << " there are " <<
std::setw(5) << years << " years, " <<
std::setw(3) << months << " months, " <<
std::setw(3) << days << " days\n";
If you just want the number of years, you can do:
date_count<year_iterator> years(bday, now);
and run with the number of years in the "years" variable. :D
Related
I have to write a code that outputs a formatted date when the user inputs 3 integers but also outputs a default date of 1/1/2019. I'm supposed to use a class and objects for this but i can't figure out how to get it to work without any arguments being passed from the object. Here's my current code
class Date
{
private:
int defaultDay = 1;
int defaultMonth = 1;
int defaultYear = 2019;
public:
Date()
{
int day = defaultDay;
int month = defaultMonth;
int Year = defaultYear;
}
void dateFormat(int day,int month,int year)
{
defaultDay = day;
defaultMonth = month;
defaultYear = year;
cout << day << "/" << month << "/" << year << endl;
}
}
int main()
{
Date setDate,
int day, month, year;
cin >> day;
while(day < 1 || day > 31)
{
cout << "Please enter a number between 1 and 31" << endl;
cin >> day;
}
cin >> month;
while(month < 1 || month > 12)
{
cout << "Please enter a number between 1 and 12" << endl;
cin >> month;
}
cin >> year;
setDate.dateFormat(day, month, year);
return 0;
}
I'm going to make minimal changes to your code to show you some things you can do.
class Date
{
private:
int day = 1;
int month = 1;
int year = 2019;
public:
// Default constructor with no arguments.
Date()
{
}
// Constructor with arguments.
Date(int _day, int _month, int _year)
{
day = _day;
month = _month;
year = _year;
}
//print me.
void print() const {
cout << day << "/" << month << "/" << year << endl;
}
}
Date firstDate(); // Will use defaults
Date secondDate(1, 11, 2019); // November 11, 2019
Here's what I did... First, I renamed your fields. You don't need defaultDay etc unless you have another reason for them.
Next, I gave you two constructors, one with no arguments (called the default constructor), and one with arguments. Classes can have as many constructors as you want, as long as the signatures are different.
Then I made a print method.
I hope this helps.
I have been trying to figure out how to accurately subtract one date from another in C++. Both will be received through user input. I thought that by creating a class, along with the use of <ctime>, I would be able to do this but I have yet to find how to do so while taking Leap years into consideration, which would be the cause for the loss of accuracy that it might have.
Here is how I was approaching the task:
#include "pch.h"
#include <iostream>
#include <ctime>
using namespace std;
class Year {
private:
struct tm date3;
struct tm date2;
struct tm date;
int FirstYear, SecondYear;
int FirstMonth, SecondMonth;
int FirstDay, SecondDay;
public:
int DateCalculus(struct tm* date, struct tm* date2);
void ResultShown();
};
int Year::DateCalculus(struct tm* date, struct tm* date2) {
struct tm date3;
date3.tm_year = date->tm_year - date2->tm_year;
date3.tm_mon = date->tm_mon - date2->tm_mon;
date3.tm_mday = date->tm_mday - date2->tm_mday;
}
void Year::ResultShown() {
cout<< date3;
}
int main() {
struct tm Date = { 0, 0, 12 };
struct tm Date2 = { 0, 0, 12 };
int Firstyear, SecondYear;
int Firstmonth, SecondMonth;
int Firstday, SecondDay;
cin >> Firstday; cout << "Day 1 " << endl;
cin >> Firstmonth; cout << "Month 1 " << endl;
cin >> Firstyear; cout << "Year 1 " << endl;
cin >> SecondDay; cout << "Day 2 " << endl;
cin >> SecondMonth; cout << "Month 2 " << endl;
cin >> SecondYear; cout << "Year 2 " << endl;
Date.tm_year = Firstyear;
Date.tm_mon = Firstmonth;
Date.tm_mday = Firstday;
Year::DateCalculus(&Date, &Date2);
cout << asctime(&Date2) << std::endl;
return 0;
}
I need to print out dates in four formats when a user enters a month, day and year.
For example if I enter "sept" for month, 17 for day and 1921 for year, it will print out:
1) 9/17/1921
2) September 17,1921
3) 1921-9-17
4) 1921-sep-17
I also do validation where if the number of days is less than 1 or greater than than the number of days for that month and the year cannot be less than 1900 or greater than 2020. If it is, month gets defaulted to "January" day to 1 and year to 2001.
When I enter jan for month 5 for day 2005 for year, I get weird values in my console 1/-858993460/-858993460 and then terminates. But when I enter mar 5 2005 i get
3/5/2005
March2005
ory corruption5
ory corruptionmar-5
I create an instance of Date and call a 3 argument constructor. The 3 argument constructor then calls a validate function which return a boolean. If the return value is false, it will call the default constructor which sets everything to january 1 2001.
//UPDATE:
Changed inital value of int index in date.cpp to -1 instead of NULL. Doing this now calls the print function four times four when I enter "jan" but I still get the weird results
1/5/2005
January2005 //This should be January 5, 2005
ory corruption5
ory corruptionmar-5
Why does the first time print is called all my member variables retain the values, but the 2nd, 3rd, and 4th time, day is missing and shows weird corruption message?
I don't know what is going on but when I also enter an invalid date such as "jan" for month but 36 for days and 2025 for year, the default constructor should set month to January, day to 1 and year to 2001 but I get garbage values
1/-858993460/-858993460
This is the first time print is called then after that it terminates.
//Header
#pragma once
#include <iostream>
#include <string>
using namespace std;
/*Add more constants if needed*/
#ifndef DATE_H
#define DATE_H
enum DateFormat { mdy1, mdy2, ymd1, ymd2 };
const int MIN_YEAR = 1900;
const int MAX_YEAR = 2020;
const string monthStr[] = //alternative: const char monthStr[] [15]=
{ "January", "February", "March", "April", "May", "June",
"July", "August", "September", "October", "November",
"December" };
const string monthStrAbbrev[] = //not strictly necessary, but helpful
{ "jan", "feb", "mar", "apr", "may", "jun",
"jul", "aug", "sep", "oct", "nov",
"dec" };
const int monthDays[] =
{ 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 };
class Date {
private:
string month;
int day, year;
bool validateDate(string, int, int);
Date();
public:
Date(string, int, int);
void print(DateFormat type);
};
#endif // !DATES_H
//Dates.cpp
#include "stdafx.h"
#include <iostream>
#include <algorithm>
#include "date.h"
using std::cout;
using std::cin;
int global;
Date::Date() : month("January"), day(1), year(2001) { cout << "INSIDE CONST" << endl; }
Date::Date(string m, int d, int y)
{
if (!validateDate(m, d, y))
{
cout << "IF FALSE" << endl;
Date();
}
else
{
month = m;
day = d;
year = y;
cout << "MONTH IS :" << month << " DAY IS: " << day << " YEAR IS: " << year << endl;
}
}
bool Date::validateDate(string m, int d, int y)
{
cout << "size is " << sizeof(monthStrAbbrev) / sizeof(monthStrAbbrev[0]) << endl;;
int index = -1;
for (int x = 0; x < 11; x++)
{
string mAbr = monthStr[x].substr (0, 3);
transform(mAbr.begin(), mAbr.end(), mAbr.begin(), (int(*) (int)) tolower);
cout << "Abbr: " << mAbr << endl;
if (m == mAbr)
{
index = x;
global = x;
cout << "x " << x << " global " << global << " Index " << index << endl;
if (d < 1 && d > monthDays[index])
{
cout << "FALSE 1" << endl;
return false;
}
if (y < MIN_YEAR || y > MAX_YEAR)
{
cout << "FALSE 2" << endl;
return false;
}
break;
}
}
if (index == -1)
{
cout << "IF NULL" << endl;
return false;
}
else
{
cout << " IF NOT NULL" << endl;
return true;
}
}
void Date::print(DateFormat type)
{
if (type == mdy1)
{
cout << global + 1 << "/" << day << "/" << year << endl;
}
else if (type == mdy2)
{
cout << monthStr[global] << day + ", " << year << endl;
}
else if (type == ymd1)
{
cout << year + "-" << (global + 1) + "-" << day << endl;
}
else if (type == ymd2)
{
cout << year + "-" << month + "-" << day << endl;
}
}
//Test.cpp
#include "stdafx.h"
#include <iostream>
#include <algorithm>
#include <string>
using namespace std;
#include "date.h"
void setDateValues(string&, int&, int&);
int main()
{
string mth;
int day, yr;
setDateValues(mth, day, yr);
transform(mth.begin(), mth.end(), mth.begin(), (int(*) (int)) tolower);
Date d1(mth, day, yr);
cout << "Date is:\n";
DateFormat type;
type = mdy1;
d1.print(type);
type = mdy2;
d1.print(type);
type = ymd1;
d1.print(type);
type = ymd2;
d1.print(type);
return 0;
}
void setDateValues(string & m, int& d, int& y)
{
cout << "Enter month: ";
cin >> m;
cout << "Enter day: ";
cin >> d;
cout << "Enter year: ";
cin >> y;
}
There is a standard library function for this: strftime().
You give it a date in a struct, and it writes a string. For your four cases, the format strings would be:
1) %m/%d/%Y
2) %B %d, %Y
3) %F
4) %Y-%b-%d
I want the program to work so that I can turn any worded month to its equivalent number.
#include <iostream>
using namespace std;
int main()
{
char month[20];
int INT_month;
cout << "Enter a month: (ex. January, February)";
cin >> month; // Let's say the input is February
if (month == "February")
INT_month = 2;
cout << "The month in its' integral form is " << INT_month << endl;
// INT_month = 2130567168 // WHY DOES IT DO THIS????
return 0;
}
One way to do it is creating a vector of month names, and using the look-up index plus one as the month number:
vector<string> months = {
"january", "february", "march", ...
};
string search = "march";
auto pos = find(months.begin(), months.end(), search);
if (pos != months.end()) {
cout << "Month number: " << distance(months.begin(), pos) + 1 << endl;
} else {
cerr << "Not found" << endl;
}
This prints 3 (demo on ideone).
Thank you for taking the time to read my first query. I'm new to C++ and am honestly exhausted. I've spent more time trying to find an IDE that supports "thread" than I have learning the language. Tried DevC++ 5.5.3, Eclipse 4.3.1 and am currently trying Visual Studio Express 2013. I think my code is solid, but of course I could be wrong. More than likely wrong, perhaps. Here's a sample:
#ifdef _MSC_VER
#define _CRT_SECURE_NO_WARNINGS
#endif
#include <iostream>
#include <cstdlib>
#include <cstdio>
#include <string>
#include <chrono>
#include <ctime>
#include <iomanip>
#include <thread>
#include "IntervalSelection.h"
#include "Acnt.h"
using namespace std;
int main(int argc, char *argv[])
{
cout << "Hello, Mommy. To begin, what is your name?\n";
char NewMommyName[40];
cin >> NewMommyName;
std::thread t1 (Account()), (NewMommyName));
Supply * pS;
std::time_t NewPumpTime = PumpTime(pS);
struct tm * ptm = std::localtime(&NewPumpTime);
std::chrono::steady_clock::time_point TP =
std::chrono::steady_clock::from_time_t(mktime(ptm));
std::this_thread::sleep_until(TP);
std::cout << " The time is now " << std::put_time (TP, "%X")<<"\nTime to pump!";
t1.join();
//The following errors are generated:
//"no instance of function template "std::put_time" matches the argument list"
//"expression must have class type" (t1.join())
//"expected a ';' - on this line: std::thread t1 (Account()), (NewMommyName));
//"left of '.join' must have class/struct/union"
//"syntax error : ')' - on this line: std::thread t1 (Account()), (NewMommyName));
//error C2040: 'NewMommyName' : 'std::thread' differs in levels of indirection
//from 'char [40]'
There seem to be plenty of folk with a great deal more experience than me who have complaints about finding thread support. Is the error mine or some bug that I can't work around? Is there an IDE I can use that offers less of a headache in this area?
Below is the more consequential of the two header files along with errors that I'm getting when I try to build:
#ifndef ACNT_H
#define ACNT_H
#include <iostream>
#include <cstdlib>
#include <cstdio>
#include <string>
#include <chrono>
#include <ctime>
#include <iomanip>
#include <thread>
#include "IntervalSelection.h"
using namespace std;
inline
std::string timeString(const std::chrono::steady_clock::time_point& tp)
{
std::time_t t = std::chrono::steady_clock::to_time_t(tp);
std::string ts = ctime(&t);
ts.resize(ts.size() - 1);
return ts;
}
inline
std::chrono::steady_clock::time_point MakeTime(int year, int mon, int day, int
hour, int min, int sec = 0)
{
struct std::tm t;
t.tm_sec = sec;
t.tm_min = min;
t.tm_hour = hour;
t.tm_mday = day;
t.tm_mon = mon - 1;
t.tm_year = year - 1900;
t.tm_isdst = -1;
std::time_t tt = std::mktime(&t);
if (tt == -1){ throw "Not a valid system time."; }
return std::chrono::steady_clock::from_time_t(tt);
}
class Supply
{
friend time_t PumpTime(Supply*);
public:
Supply()
{
double MilkOz = 0.0;
long long tempInterval = 0;
char* dayOrnight;
int year, mon, day, hour, min, sec = 0;
char morning[5] = "a.m.";
char evening[5] = "p.m.";
cout << "\nHow many ounces of milk do you currently have in your
supply?\n";
cout << "For greater accuracy, feel free to enter this value in decimal
form (e.g. 4.5): ";
cin >> MilkOz;
cout << "\nIdeally, how often would you like to pump?\n";
tempInterval = IntervalSelection();
std::chrono::steady_clock::time_point NOW =
std::chrono::steady_clock::now();
time_t currentTp = std::chrono::steady_clock::to_time_t(NOW);
struct tm* local;
local = localtime(¤tTp);
switch (local->tm_hour){ case 12: dayOrnight = evening; break; case 0:
local->tm_hour = (local->tm_hour) + 12; dayOrnight = morning; break; }
if (local->tm_hour > 12){ local->tm_hour = (local->tm_hour) - 12;
dayOrnight = evening;; }
else if (local->tm_hour < 12){ dayOrnight = morning; }
printf("The time is now %d: %d: %d %s", local->tm_hour, local->tm_min,
local->tm_sec, dayOrnight);
cout << "\n";
std::chrono::steady_clock::time_point tNew =
std::chrono::steady_clock::from_time_t(currentTp);
static std::chrono::steady_clock::time_point tt = tNew +
std::chrono::hours(tempInterval);
std::time_t structable, structable2 =
std::chrono::steady_clock::to_time_t(tt);
struct tm* localNew;
localNew = localtime(&structable);
switch (localNew->tm_hour){ case 12: dayOrnight = evening; break; case 0:
localNew->tm_hour = (localNew->tm_hour) + 12; dayOrnight = morning; break; }
if (localNew->tm_hour > 12){ localNew->tm_hour = (localNew->tm_hour) - 12;
dayOrnight = evening; }
else if (localNew->tm_hour < 12){ dayOrnight = morning; }
printf("Your new pump time is scheduled for %d: %d: %d %s",
localNew->tm_hour, localNew->tm_min, localNew->tm_sec, dayOrnight);
cout << "\nTo accept this time enter 'yes'. To specify a different time,
enter 'no'.\n";
char choice[4];
const char* yes = "yes";
const char* no = "no";
cin >> choice;
if (strncmp(choice, yes, 1) == 0)
{
std::string date = ctime(&structable);
date.resize(date.size() - 1);
cout << "Thank you. Your next pump time is confirmed for " << date;
std::time_t tpNewest = structable2;
}
else if (strncmp(choice, no, 1) == 0)
{
cout << "Please enter an exact date to schedule your next pump
time.\n";
cout << "Enter the current year: ";
cin >> year;
cout << "\nEnter a numerical value for the month. For example, the
number one is equivalent to the month of January: ";
cin >> mon;
cout << "\nEnter the numerical day of the month: ";
cin >> day;
cout << "\nEnter the hour: ";
cin >> hour;
cout << "\nEnter the minutes: ";
cin >> min;
static auto tpNew = MakeTime(year, mon, day, hour, min, sec);
cout << "Your next pump time is scheduled for " <<
timeString(tpNew) << endl;
std::time_t tpNewest = std::chrono::steady_clock::to_time_t(tpNew);
}
}
double entry = 0;
double getSupply(double MilkOz, double entry)
{
TotalSupply = MilkOz + entry;
return TotalSupply;
}
~Supply(){}
private:
double TotalSupply;
std::time_t tpNewest;
};
time_t PumpTime(Supply* pS)
{
return pS->tpNewest;
}
class Baby
{
public:
Baby()
{
double lbs = 0.0;
double oz = 0.0;
char pbName[40];
char pbGender[40];
cout << "\nWhat is your Baby's name?" << endl;
cin >> pbName;
strncpy(BabyName, pbName, 40);
cout << "And is " << this->BabyName << " a Boy or a Girl?\n";
cin >> pbGender;
strncpy(BabyGender, pbGender, 5);
if (strncmp(this->BabyGender, "boy", 1) == 0)
{
cout << "\nWhat is his weight in pounds and ounces?\n";
cout << "For example: My baby weighs 16 lbs and 4 oz. \n";
cout << "Pounds: ";
cin >> lbs;
cout << "\n Ounces: ";
cin >> oz;
Baby::getWeight(lbs, oz);
}
else if (strncmp(this->BabyGender, "girl", 1) == 0)
{
cout << "\nWhat is her weight in pounds and ounces?" << endl;
cout << "For example: My baby weighs 16 lbs and 4 oz. \n";
cout << "Pounds: ";
cin >> lbs;
cout << "\nOunces: ";
cin >> oz;
Baby::getWeight(lbs, oz);
}
cout << "\n" << this->BabyName << "'s current weight is " <<
this->BabyWeight << " pounds";
}
double getWeight(double pounds, double ounces)
{
ounces = ounces * 1 / 16;
BabyWeight = pounds + ounces;
return BabyWeight;
}
~Baby(){}
private:
char BabyName[40];
char BabyGender[5];
double BabyWeight;
};
class Mommy
{
public:
Mommy(char* paName)
{
strncpy(MommyName, paName, 40);
}
~Mommy(){}
private:
char MommyName[40];
Baby b;
Supply s;
};
class Account
{
public:
Account(char* paName) :m(paName)
{
strncpy(Name, paName, 40);
}
~Account(){}
private:
char Name[40];
Mommy m;
};
#endif
//ERRORS:
//expression must have class type -t1.join();
//expected a type specifier -std::thread t1 (Account()), (NewMommyName));
//left of '.join' must have class/struct/union
//syntax error : '(' -std::thread t1 (Account()), (NewMommyName));
You have extra parentheses in this line (including an unclosed one):
std::thread t1 (Account()), (NewMommyName));
It should be:
std::thread t1 (Account, (NewMommyName));
Also - your call to std::put_time is incorrect. put_time takes a const std::tm* not time_point. You would need to convert it to a std::tm in order to pass it to put_time
Without the rest of the code, it is hard to diagnose more than those couple of errors. I would suspect your issue is not compiler support.