Generating Year, Months, Weeks and Days from user input - c++

I’m creating an application that generates Year, month, weeks and days from a user input
I’ve tried this but only the years and months work
So for example when I put in 30 days, it says 1 month, 2 weeks and 2 days instead of just 1 month
Thanks
// Description: This program prompts the user for an integer, which will represents the total
////number of days; The program then will break it apart into years, months, weeks, and days ////(each one of these will have their own local variables), and once this is done, the outcome will be //displayed on the screen.
//Enter no.of days : 1234Years : 3Months : 4Weeks : 2Days : 5
#include <iostream>
#include <cmath>
using namespace std;
const int daysInWeek = 7;
const int days_in_month = 30;
const int days_in_year = 365;
const int days_in_days = 1;
int main()
{
//Local variables
int totalDays;
int years;
int months;
int weeks;
int days;
//program info/intro
cout << "My name is Diana\n";
cout << "Program 1: Convert Number of Days to Years, Months, Weeks, and Days" << endl;
cout << "---------------------------------------------------------------- ----- \n";
//get numbers and develop math progress
cout << "Enter the total number of days : ";
cin >> totalDays;
years = totalDays / days_in_year;
months = (totalDays % days_in_year) / days_in_month;
weeks = (days_in_month % daysInWeek);
/*weeks = (totalDays%days_in_year) / daysInWeek;*/
days = (totalDays% days_in_year) % daysInWeek;
// Display it in the screen
cout << " " <<
cout << "Years = " << years <<
cout << "Months = " << months << endl;
cout << "Weeks = " << weeks << endl;
cout << "Days = " << days << endl;
system("pause");
return 0;
}

As already suggested a better approach would be to keep track of the remaining days:
years = totalDays / days_in_year;
totalDays %= days_in_year;
months = totalDays / days_in_month;
totalDays %= days_in_month;
weeks = totalDays / days_in_week;
totalDays %= days_in_week;
days = totalDays;

Related

Get seconds until end of month in C++

I have a requirement to get time interval until end of month in C++. Are there any C++ APIs which can easily do that for me?
I need to start a timer which will expire at the first day of next month at 00:00:00 hours. For that, I need to compute the time interval i.e. number of seconds from now till end of this month.
Its rather straight foward. Get the difference in number of days between now and the last day of the month. Then get the number of seconds in a day.
Now you have the number of seconds till the end of the month, now subtract that with the number of seconds right now so far today and you will get the number of seconds until the end of the month.
#include <time.h>
#include <iostream>
using namespace std;
int main(){
int day1,month1,year1;
int day2,month2,year2;
int i,temp,DaysDiff=0;
int month[]={31,28,31,30,31,30,31,31,30,31,30,31};
int totalDiffDaysSecs=0;
int nowSeconds=0;
int expire=1000;
time_t t = time(0); // get time now
struct tm * now = localtime( & t );
cout<<"\n";
day1=now->tm_mday;
month1=(now->tm_mon + 1);
year1=(now->tm_year + 1900);
day2=31;
month2=7;
year2=2015;
temp=day1;
for(i=month1;i<month2+(year2-year1)*12;i++){
if(i>12){
i=1;
year1++;
}
if(i==2){
if(year1%4==0 && (year1%100!=0 || year1%400==0))
month[i-1]=29;
else
month[i-1]=28;
}
DaysDiff=DaysDiff+(month[i-1]-temp);
temp=0;
}
cout <<"Current Time = "<< now->tm_hour << ":" << now->tm_min << "."<<now->tm_sec<<"\n";
cout <<"Today's date "<< (now->tm_year + 1900) << '-' << (now->tm_mon + 1) << '-' << now->tm_mday << " \n";
cout <<"Target date "<< year2 << '-' << month2 << '-' << day2 << " \n";
DaysDiff=DaysDiff+day2-temp;
cout<<"Target Month = "<<i<<"\n";
cout<<"Days in Target month = "<<month[i-1]<<"\n";
cout<<"Days diff Today - Target Month = "<<DaysDiff<<" \n";
totalDiffDaysSecs=DaysDiff*24*60*60;
nowSeconds= (now->tm_hour * 3600) + (now->tm_min * 60)+ now->tm_sec;
cout<<"Total seconds in a day = "<<24*60*60<<" \n";
cout<<"current total seconds so far today = "<< nowSeconds <<"\n";
cout<<"Total number of seconds in "<< DaysDiff <<" days = "<< totalDiffDaysSecs <<"\n";
cout<<"\n\n";
while(expire>0){
t = time(0); // get time now
now = localtime( & t );
nowSeconds= (now->tm_hour * 3600) + (now->tm_min * 60)+ now->tm_sec;
expire=totalDiffDaysSecs - nowSeconds;
cout <<"Seconds until end of month = "<< expire <<" \r";
}
cout<<"\n\n";
cout<<"Countdown expired.\n\n";
return 0;
}

Converting seconds to hours and minutes and seconds

#include <cstdio>
#include <iostream>
using namespace std;
int main ()
{
int seconds, hours, minutes;
cin >> seconds;
hours = seconds/3600;
cout << seconds << " seconds is equivalent to " << int(hours) << " hours " << seconds%(hours*60)
<< " minutes " << (seconds%(hours*3600))-((seconds%(hours*60))*60) << " seconds.";
}
For some reason, this program works with only numbers above 3600. Does anyone know how to fix this problem? Whenever I do a number below 3600, the screen shows up with a message from Windows saying that the program has stopped working.
Try this out instead, tested and works:
int seconds, hours, minutes;
cin >> seconds;
minutes = seconds / 60;
hours = minutes / 60;
cout << seconds << " seconds is equivalent to " << int(hours) << " hours " << int(minutes%60)
<< " minutes " << int(seconds%60) << " seconds.";
Because minutes is seconds/60, dividing it by 60 again is equivalent to diving seconds by 3600, which is why it works.
seconds/3600 is integer division, so for seconds < 3600, hours is 0, then things like seconds%(hours*3600) becomes seconds % 0, causing a division-by-zero.
Let's first get the logic right. Suppose you want to write 5000 seconds as x hours y minutes z seconds, such that all three are integers and neither y nor z is greater than 59. What do you do?
Well, you can first write it as q minutes z seconds, such that both are integers and z is not greater than 59. That's easy:
q = 5000 / 60 = 83 // integer division
z = 5000 % 60 = 20
So 5000 seconds is 83 minutes 20 seconds. Now how do you write 83 minutes into x hours y minutes, such that both are integers and y is no greater than 59? You do the same thing:
x = 83 / 60 = 1
y = 83 % 60 = 23
OK, let's generalize this:
int total, seconds, hours, minutes;
cin >> total;
minutes = total / 60;
seconds = total % 60;
hours = minutes / 60;
minutes = minutes % 60;
cout << total << " seconds is equivalent to " << hours << " hours " << minutes
<< " minutes " << seconds << " seconds.\n" ;
You've got a divide-by-zero problem here:
seconds % (hours*60);
hours is 0 by virtue of integer division.
hours = seconds/3600;
From what you're trying to do, you should consider conditional logic to print the minutes if the total number of seconds is greater than 3600. You'll also want to investigate similar logic in the next part of your print stream.
My C++ is rusty, so forgive if this isn't exactly valid syntax:
cout << (seconds > 3600 ? seconds % (hours*60) : seconds) << endl;
Try this:
int totalSecond;
cin >> totalSecond;
int hour = totalSecond / 3600;
int minute = (totalSecond % 3600) / 60;
int second = totalSecond % 60;
cout << hour << ":" << minute << ":" << second << endl;
Assuming that totalSeconds is the number of seconds since midnight and is less than 86400
With c++20 this gets pretty easy using std::chrono::hh_mm_ss:
#include <iostream>
#include <chrono>
int main ()
{
int seconds;
std::cin >> seconds;
std::chrono::hh_mm_ss time{std::chrono::seconds(seconds)};
std::cout << seconds << " seconds is equivalent to " << time.hours().count() << " hours " << time.minutes().count()
<< " minutes " << time.seconds().count() << " seconds.";
}
by using function;
#include<iostream>
using namespace std;
int hour(int h)
{
int second;
//second=(h/3600);
if (h>3600)
second=h/3600;
else
second=(h/3600);
return (second);
}
int minute(int m)
{
int second2;
second2=( );
return(second2);
}
int second(int s)
{
int second3;
second3=((s-3600)%60);
return (second3);
}
void main()
{
int convert;
cout<<"please enter seconed to convert it to hour\b";
cin>>convert;
cout<<"hr : min : sec \n";
cout<<hour(convert)<<":"<<minute(convert)<<":"<<second(convert)<<endl;
system("pause");
}
Until now none of the presented solution have in count the day duration. I had to write a clock to use in arduino, the millis() function return milliseconds since turn on, to get seconds just divide by 1000.
void showTime(unsigned long seconds){
printf( "seconds : %lu ", seconds);
int hh = (seconds/3600) %24;
int mm = (seconds/60) %60;
int ss = seconds%60;
printf( " Time : %2d:%02d:%02d\n", hh, mm,ss);
}
showTime( 0*24*3600 + 4*3600+35*60+25); // 0d+4hs+35m+25s;
showTime( 2*24*3600 + 1*3600+45*60+59); // 2d+1hs+45m+59s;
showTime(40*24*3600 + 10*3600+ 5*60+10); // 40d+10hs+5m+10s;
wath print:
seconds : 189325 Time : 4:35:25
seconds : 6359 Time : 1:45:59
seconds : 3492360 Time : 10:06:00
Using std::chrono::duration_cast, one can simply write (refer std::chrono::duration for more options):
#include <chrono>
#include <iostream>
using namespace std::chrono;
int main() {
int s; std::cin >> s;
seconds sec(s);
std::cout << duration_cast<hours>(sec).count() << ':'
<< duration_cast<minutes>(sec).count() % 60 << ':'
<< sec.count() % 60;
}
One string convertion from seconds to hh:mm:ss format:
sprintf(tempBuffer, "%02u:%02u:%02u", _time / 3600, (_time % 3600) / 60, _time % 60);
Try this
int h,m,s;
cout << "Time in Seconds = ";
cin >> s;
cout << "H:M:S - " << s / 3600 << ":" << (s % 3600) / 60 << ":" << s % 60;
Input:
Time in Seconds = 25300
Output:
H:M:S - 7:1:40
Have a look at this code:
#include <iostream>
using namespace std;
int main()
{
int seconds;
cout << "Enter an integer for seconds: ";
cin >> seconds;
int minutes = seconds / 60;
int remainingSeconds = seconds % 60;
cout << seconds << " seconds is " << minutes <<
" minutes and " << remainingSeconds << " seconds " << endl;
return 0;
}

C++ Output error

I have a problem with my program and I would appreciate help.
It's supposed to allow you to enter an account number, a service code, and the number of minutes the service was used. The program then calculates the bill and it varies depending on your service. When I execute the program, it doesn't allow you to enter anything.
Regular service:$10.00 plus first 50 minutes free. Charges for over 50 minutes are $0.20 per minute.
Premium service:
$25.00 plus:
a)
For calls made from 6:00 am to 6:00 pm, the first 75 minutes are free; charges for over
75 minutes are $0.10 per minute.
b)For calls made from 6:00 pm to 6:00 am, the first 100 minutes are free; charges for over 100 minutes are $0.05 per minute.
Here is the program that I've typed.
#include "stdafx.h"
#include <iostream>
#include <iomanip>
#include <string>
using namespace std;
int main()
{
int minutes = 0,
day_minutes = 0, //minutes used during the day
night_minutes = 0; //minutes used during the night
string service_code,
account_number;
double final_amount,
final_damount, //final amount for day minutes
final_namount = 0; //final amount for night minutes
cout << "Please enter your account number: ";
cin >> account_number;
cout << "Please enter your service code (r or R for regular service and p or P for premium service): ";
cin >> service_code;
if (service_code == "r")
{
cout << "Please enter the amount of minutes used: " << minutes << endl;
}
if (minutes <= 50)
{
final_amount = 10;
cout << "Your final amount is $: " << final_amount << endl;
}
if (minutes > 50)
{
final_amount = (minutes * 0.20) + 10;
cout << "Your final amount is $: " << final_amount << endl;
}
else if (service_code == "p")
{
cout << "Please enter the amount of minutes used during the day: " << day_minutes << endl;
cout << "Please enter the amount of minutes used during the night: " << night_minutes << endl;
}
if (day_minutes <=75)
{
final_damount = 0;
final_amount = final_damount + final_namount + 20;
}
if (day_minutes > 75)
{
final_damount = day_minutes * 0.10;
final_amount = final_damount + final_namount + 20;
}
if (night_minutes <= 100)
{
final_namount = 0;
final_amount = final_damount + final_namount + 20;
}
if (night_minutes > 100)
{
final_namount = night_minutes * 0.05;
final_amount = final_damount + final_namount + 20;
cout << "Your final amount is: $ " << final_amount << endl;
}
else
cout << "Error, this program does not accept negative numbers.\n";
return 0;
}
Does anyone the problem to my program? Thank you.
In your code you never specify to ask for user input (read from any input streams or files), hence it doesn't ask for any input.
You will probably want to somewhere do something such as cin or cin.readline or any of several other various methods to read the user's input from stdin.
To avoid duplicating other questions I'm not putting further details here.

C++ compare dates to get age

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(&current);
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

Convert seconds to Days, Minutes and Seconds

Hey everyone. I've continuing to learn C++ and I've been set the 'challenge' of converting seconds to format as the Days,Minutes and Seconds.
For example: 31600000 = 365 days, 46 minutes, 40 seconds.
using namespace std;
const int hours_in_day = 24;
const int mins_in_hour = 60;
const int secs_to_min = 60;
long input_seconds;
cin >> input_seconds;
long seconds = input_seconds % secs_to_min;
long minutes = input_seconds / secs_to_min % mins_in_hour;
long days = input_seconds / secs_to_min / mins_in_hour / hours_in_day;
cout << input_seconds << " seconds = "
<< days << " days, "
<< minutes << " minutes, "
<< seconds << " seconds ";
return 0;
It works and comes up with the correct answer but after completing it I looked at how other people had tackled it and theirs was different. I'm wondering If I'm missing something.
Thanks, Dan.
this seems to me to be the easiest way to convert seconds into DD/hh/mm/ss:
#include <time.h>
#include <iostream>
using namespace std;
time_t seconds(1641); // you have to convert your input_seconds into time_t
tm *p = gmtime(&seconds); // convert to broken down time
cout << "days = " << p->tm_yday << endl;
cout << "hours = " << p->tm_hour << endl;
cout << "minutes = " << p->tm_min << endl;
cout << "seconds = " << p->tm_sec << endl;
I hope it helps!
Regards,
Stoycho
One of the things about programming is that there is never just one way to do something. In fact if I were to set my mind to it, I might be able to come up with a dozen completely different ways to accomplish this. You're not missing anything if your code meets requirements.
For your amusement, here's a way to format up hours:minutes:seconds under Windows (elapsed is a double & represents number of seconds elapsed since... something)
sprintf_s<bufSize>(buf, "%01.0f:%02.0f:%02.2f", floor(elapsed/3600.0), floor(fmod(elapsed,3600.0)/60.0), fmod(elapsed,60.0));
I think is the challenge from Stephen Prata's book. I did it as follows:
#include <iostream>
using namespace std;
int main()
{
long input_seconds = 31600000;
const int cseconds_in_day = 86400;
const int cseconds_in_hour = 3600;
const int cseconds_in_minute = 60;
const int cseconds = 1;
long long days = input_seconds / cseconds_in_day;
long hours = (input_seconds % cseconds_in_day) / cseconds_in_hour;
long minutes = ((input_seconds % cseconds_in_day) % cseconds_in_hour) / cseconds_in_minute;
long seconds = (((input_seconds % cseconds_in_day) % cseconds_in_hour) % cseconds_in_minute) / cseconds;
cout << input_seconds << " seconds is " << days << " days, " << hours << " hours, " << minutes << " minutes, and " << seconds << " seconds.";
cin.get();
return 0;
}
For example: 31600000 = 365 days, 46 minutes, 40 seconds.
Really?
$ bc
365*24*60*60 + 46*60 + 40
31538800
365*24*60*60 + 1066*60 + 40
31600000
Did you mean "convert the input into days, hours, minutes and seconds, and then discard the hours" or "convert the input into days, total minutes within a day (i.e. can be more than 60), and seconds"?
In the second case I think you should replace the instruction for minutes with
long minutes = input_seconds / secs_to_min % (mins_in_hour * hours_in_day);