I'm brand new to C++. In my Programming I class, I've been given the following assignment as a midterm:
-Calculate how many days you have been alive
(epoch time from 01/01/1970 stored by seconds)
-Command Line Args for Birth Year, Birth Month, Birth Day
Now, I've already figured out the function itself for actually subtracting two dates from each other, and I've figured out how to grab the current date and stick it in that function. The problem I'm having is how to get the user's entered date and send that to the function.
I've been playing with a "test" piece of code to get this to work, unfortunately when I try to compile this I just get a MOUNTAIN of errors that I don't understand at all, so I'm clearly doing something wrong.
#include <iostream>
#include <ctime>
using namespace std;
struct tm a(int year, int month, int day)
{
struct tm birth {0};
cin >> year >> endl;
cin >> month >> endl;
cin >> day >> endl;
birth.tm_year = year - 1900;
birth.tm_mon = month;
birth.tm_mday = day;
return birth;
}
int main()
{
int year, month, day;
cout << "Enter a year, month, and day: " << endl;
cin >> year >> month >> day >> endl;
tm a(year, month, day);
time_t x = mktime(&a);
time_t y = time(0);
if ( x != (time_t)(-1) && y != (time_t)(-1) )
{
double difference = difftime(y, x) / (60 * 60 * 24);
cout << ctime(&x);
cout << ctime(&y);
cout << "difference = " << difference << " days" << endl;
}
return 0;
}
I've tried googling some of these errors, and the results I'm seeing keep talking about "pointers". I have no clue what pointers are, and flipping through our textbook, it looks like something that's about three or four chapters ahead of where we are now. I tried asking my professor about this the other day, and he just sort of giggled and said something to the effect of "Well yeah, that's the point of the midterm." I don't understand if that means I'm supposed to figure out pointers on my own or if I'm not supposed to use them.
I'm trying to get a year, month, and day from arguments entered by the user at the point of execution and stick them into a struct tm so that my function at the bottom will work.
EDIT: I figured out that I am trying to use the struct like a function, which is wrong. I have made the following changes:
#include <iostream>
#include <ctime>
using namespace std;
struct tm bday(int year, int month, int day)
{
struct tm r {0};
r.tm_year = year - 1900;
r.tm_mon = month;
r.tm_mday = day;
return r;
}
int main()
{
int year, month, day;
cout << "Enter a year, month, and day: " << endl;
cin >> year >> endl;
cin >> month >> endl;
cin >> day >> endl;
struct tm a = bday(year, month, day);
time_t x = mktime(&a);
time_t y = time(0);
if ( x != (time_t)(-1) && y != (time_t)(-1) )
{
double difference = difftime(y, x) / (60 * 60 * 24);
cout << ctime(&x);
cout << ctime(&y);
cout << "difference = " << difference << " days" << endl;
}
return 0;
}
Now getting the following errors when compiling:
filename.cpp:22:17: error: no match for 'operator>>'
filename.cpp:23:18: error: no match for 'operator>>'
filename.cpp:24:16: error: no match for 'operator>>'
This is not correct:
cin >> year >> endl;
You cannot read anything into endl. You probably confused input with output where std::cout << x << std::endl; is a common pattern. However, as a sidenote, you dont need endl after each line for output either. endl not only adds a newline character, but also flushes the stream. If you just want to start a new line then use \n only.
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'm working on my Intro to C++ homework right now, and just got stuck on this last bit and would really appreciate some help.
The directions for the homework are:
Ensure that the hour value is in the range 0 – 23; if it is not, set the hour to 1.
Ensure that the minute value is in the range 0 – 59; if it is not, set the minute to 0.
Ensure that the second value is in the range 0 – 59; if it is not, set the second to 0.
Provide a set function for each data member to validate the input going into the data member, using the values above.
Also, provide a get function for each data member to retrieve its value.
Provide a member function displayTime() that displays the hour, minute and second, each separated by a colon (Example: 3:45:29). displayTime should use the get functions to retrieve the data in the data members.
Write a test program that demonstrates class Time’s capabilities as follows:
1.Prompt for hour, minute and second.
2.Create a Time object passing the values entered in response to the prompt(s) above.
3.Call displayTime to display the “Initial Time”.
4.Prompt again for hour, minute and second, and call the set methods for each of the 3 data members.
5.Call displayTime again to display the “Modified Time”.
My current code for my project beginning with .cpp file:
#include <iostream>
using namespace std;
class Time {
public:
//Time constructor
Time(int hour, int minute, int second)
{
setTime(hour, minute, second);
}
void setTime(int input_hour, int input_minute, int input_second)
{
setHour(input_hour);
setMinute(input_minute);
setSecond(input_second);
}
//set hour function
void setHour(int input_hour)
{
if (input_hour >= 0 && input_hour < 24)
{
hour = input_hour;
}
else
hour = 1;
}
//set minute function
void setMinute(int input_minute)
{
if (input_minute >= 0 && input_minute < 60)
{
minute = input_minute;
}
else
minute = 0;
}
//set second function
void setSecond(int input_second)
{
if (input_second >= 0 && input_second < 60)
{
second = input_second;
}
else
second = 0;
}
//get functions
int getHour()
{
return hour;
}
int getMinute()
{
return minute;
}
int getSecond()
{
return second;
}
// display function
void displayTime()
{
cout << "Time is " << hour << ":" << minute << ":" << second;
}
//private data members
private:
int hour;
int minute;
int second;
};
Now the .h file:
#include <iostream>
#include "Time.h"
using namespace std;
int main()
{
int hour, minute, second;
cout << "Enter the hour: ";
cin >> hour;
cout << "Enter the minute: ";
cin >> minute;
cout << "Enter the second: ";
cin >> second;
Time printTime{ hour, minute, second };
cout << "Time is " << printTime.getHour() << ":" << printTime.getMinute() << ":" << printTime.getSecond();
cout << "\n\nEnter the hour: ";
cin >> hour;
cout << "Enter the minute: ";
cin >> minute;
cout << "Enter the second: ";
cin >> second;
cout << "Time is " << setTime();
//the two lines to keep my debugger from crashing
std::cin.ignore();
std::cin.get();
}
I've gotten through 1-3 fine, but its steps 4 and 5 thats throwing me off. I'm not entirely sure what I'm supposed to be doing here. I understand what is supposed to happen. It's supposed to ask the user again to input data, and then its supposed to spit out 1:0:0 which is the "modified time" via the set functions (I think), but I'm not sure how to code it properly. I've got a feeling its something very simple, but again, I'm not sure what to do. "The third to the last line of cout << "Time is " << setTime(); obviously doesn't work. This is the first time I've ever learned how to program, so I'm not entirely sure what to do. Anyway, thank you for any and all help.
From what I can understand, you just have to change the time using the set functions you have previously created. Something like this: (untested)
EDIT: there is printTime.displayTime();use it!
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
int main(){
int hour, minute, second;
cout << "Enter the hour: ";
cin >> hour;
cout << "Enter the minute: ";
cin >> minute;
cout << "Enter the second: ";
cin >> second;
Time printTime{ hour, minute, second };
printTime.displayTime();
cout << "\n\nEnter the hour: ";
cin >> hour;
//Change the hour, minutes, and seconds - then display again
printTime.setHour(hour);
cout << "Enter the minute: ";
cin >> minute;
printTime.setMinute(hour);
cout << "Enter the second: ";
cin >> second;
printTime.setSecond(hour);
//Modified time
printTime.displayTime();
}
I'm new in programming and new in here.
Sorry for stupid question but i have problem with result in my "calculate your age in seconds" code. It gives me weird result like 6.17725e+10 or -6.17414e+10.
Program isn't finished yet but everything except results looks fine (i don't get any error.
Sorry again and I hope for your understanding:)
#include <iostream>
using namespace std;
void title()
{
cout << "Age Calculator" << endl << endl;
}
int byear()
{
cout << "Enter your birth year: ";
int by;
cin >> by;
return by;
}
int bmonth()
{
cout << "Enter your birth month: ";
int bm;
cin >> bm;
return bm;
}
int bday()
{
cout << "Enter your birth day: ";
int bd;
cin >> bd;
return bd;
}
int cyear()
{
int cy;
cout << "Enter current year ";
cin >> cy;
return cy;
}
int cmonth()
{
cout << "Enter current month: ";
int cm;
cin >> cm;
return cm;
}
int cday()
{
cout << "Enter current day: ";
int cd;
cin >> cd;
return cd;
}
void calculate(int by, int bm, int bd, int cy)
{
double y = 31104000;
long double cby = y * by;
long double cbm = 259200 * bm;
long double cbd = 8640 * bd;
long double ccy = 31104000 * cy;
cout << endl << cby << endl;
cout << endl << ccy << endl;
cout << endl << ccy - cby << endl;
}
int main()
{
title();
int by = byear();
int bm = bmonth();
int bd = bday();
int cy = cyear();
int cm = cmonth();
int cd = cday();
calculate(by, bm, bd, cy);
cin.get();
return 0;
}
Like Kenny Ostrom commented, the shown values may look strange due to the scientific notation used by cout. To show all digits, you can change cout's precision using cout.precision(your_precision_here). See question below.
How do I print a double value with full precision using cout?
First, the numeric format you are confused by is "scientific notation". That will be enough info to open up a world of google searches, or you can just force it not to print in scientific notation.
Second, you really want to use a time library for any calendar stuff. It will handle all kinds of calendar weirdness for you, including leap years. Fortunately we have time.h
Third, I recommend using an integer type for seconds, partly to avoid rounding errors and ugly decimals, but mainly because that's what time.h uses. Just make sure it is big enough. My compiler uses a 64 bit integer for time_t, so I used that:
#include <time.h>
#include <memory>
time_t get_age_in_seconds(int year, int month, int day)
{
struct tm birthday;
memset(&birthday, 0, sizeof(birthday));
birthday.tm_year = year - 1900; // years since 1900
birthday.tm_mon = month - 1; // months since January (0,11)
birthday.tm_mday = day; // day of the month (1,31)
time_t birthday_in_seconds = mktime(&birthday);
time_t now = time(NULL);
return now - birthday_in_seconds;
}
Don't use doubles to do the calculation. You're not going to have any fractional values since you're not doing any division.
More importantly, look into mktime(), time(), and difftime(). You should be using these to do your calculation.
Hi guys I'm not really understanding how I would separate the users inputs when using getline(). For example the user inputs his birth date and from that I extract the month, date, and year from that.
eg.) for Sunday, January 2, 2010. I have
int main()
{
string inputStream;
string date, month, day, year;
string i;
string j;
getline(cin, inputStream);
//cin >> date >> month >> day >> year;
i = inputStream.substr(0, inputStream.find(","));
j = inputStream.substr(inputStream.find(","), inputStream.find(","));
date = i;
month = j;
cout << month << " " << day << " was a " << date << " in" << year << endl;
return0;
}
For i it works properly and will display sunday but for j it doesn't seem to want to work. Can someone show me where I went wrong? I'm not sure how I would extract the next value after the date.
Following modifications are done in your code to parse the day, date, month and year from the input string (as per your input format) successfully.
#include <iostream>
using namespace std;
int main()
{
string inputStream;
string date, month, day, year;
string i;
string j;
getline(cin, inputStream);
// day
day = inputStream.substr(0, inputStream.find(","));
// month
int pos1 = inputStream.find(",") + 2; // Go ahead by 2 to ignore ',' and ' ' (space)
int pos2 = inputStream.find(" ", pos1); // Find position of ' ' occurring after pos1
month = inputStream.substr(pos1, pos2-pos1); // length to copy = pos2-pos1
// date
int pos3 = inputStream.find(",", pos2); // Find position of ',' occurring after pos2
date = inputStream.substr(pos2, pos3-pos2); // length to copy = pos3-pos2
// year
year = inputStream.substr(pos3+2); // Go ahead by 2 to ignore ',' and ' ' (space)
cout << "day = " << day << endl;
cout << "date = " << date << endl;
cout << "month = " << month << endl;
cout << "year = " << year << endl;
return 0;
}
Hope this helps you.
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