one of the problems I'm working on requires an input of two time values (being in hours, minutes and seconds)in a 24h00 format. I have already declared my variables, input and output statements with regards to my main program. I'm just having trouble with my void statement CalcDiff to calculate the difference of the two time inputs. All values have been declared of type int. Should inputs(eg. sec and sec2) be compared first to see which is greater before calculating the difference? I'm assuming the order of variables would be important too(calculating the difference of the hours before the minutes, before the seconds)? I'm new to C++ so my apologies if I'm missing anything obvious.
// Computes time difference of two time periods in 24h00 format
// Time periods are input
#include <iostream>
using namespace std;
int seconds,seconds2, minutes, minutes2, hours, hours2;
void CalcDiff(int seconds, int seconds2 int minutes, int minutes2, int
hours, int hours2);
int main()
{
int sec, sec2, min, min2, hr, hr2, diff;
cout << "Enter the first time." << endl;
cout << "Enter hours, minutes and seconds: ";
cin >> hr >> min >> sec;
cout << "Enter the second time." << endl;
cout << "Enter hours, minutes and seconds: ";
cin >> hr2 >> min2 >> sec2;
CalcDiff(int sec, int sec2, int min, int min2, int hr, int hr2,
diff);
cout << endl << "Difference in times: " << hr << ":" << min << ":"
<< sec;
cout << " - " << hr2 << ":" << min2 << ":" << sec2;
return 0;
}
void CalcDiff(int seconds, int seconds2, int minutes, int minutes2, int
hour, int hour2, diff)
Use <chrono> plus an existing library.
#include "date.h"
#include <iostream>
int
main()
{
std::chrono::seconds t1, t2;
std::cout << "Enter the first time [h]h:mm:ss: ";
std::cin >> date::parse("%T", t1);
if (std::cin.fail())
return 1;
std::cout << "Enter the second time [h]h:mm:ss: ";
std::cin >> date::parse(" %T", t2);
if (std::cin.fail())
return 1;
std::cout << date::format("Difference in times: %T\n", t1 - t2);
}
The above library is free, open-source, and being proposed for standardization.
I had the same problem and my solution was this code, my perspective is to get both times in seconds and then subtract them to know the difference. time calculations are made inside the IF statement. the rest of the code is to print the results, I added many variables to try to make it more explicit and understandable.
#include <iostream>
using namespace std;
int main()
{
int h1,h2,m1,m2,s1,s2;
long TotalSeconds = 0;
cout << "Enter the first time." << endl;
cout << "Enter hours, minutes and seconds: ";
cin >> h1 >> m1 >> s1;
cout << "Enter the second time." << endl;
cout << "Enter hours, minutes and seconds: ";
cin >> h2 >> m2 >> s2;
// Difference Between Times IN Seconds
// this code must be in your function
if( h1 > h2 ){
TotalSeconds += 86400 - ((h1*3600)+(m1*60)+(s1));
TotalSeconds += ((h2*3600)+(m2*60)+(s2));
}else{
// Time 2 - Time 1
TotalSeconds = ((h2*3600)+(m2*60)+(s2)) - ((h1*3600)+(m1*60)+(s1));
}
cout << "Total Seconds: " << TotalSeconds << endl;
cout << "Time Difference :\t";
long hours, minutes, seconds;
hours = TotalSeconds / 3600;
cout << hours << ":";
TotalSeconds -= hours*3600;
minutes = TotalSeconds / 60;
cout << minutes << ":";
TotalSeconds -= minutes*60;
seconds = TotalSeconds;
cout << seconds << endl;
return 0;
}
Another Example using C' Style, in this example you must input time string like this 01:23:11
#include <stdio.h>
#include <stdlib.h>
int main()
{
int h1,h2,m1,m2,s1,s2;
long segundos = 0;
// Hora Inicial
scanf("%i : %i : %i",&h1,&m1,&s1);
// Hora Final
scanf("%i : %i : %i",&h2,&m2,&s2);
// HORAS
if( h1 > h2 ){
segundos += 86400 - ((h1*3600)+(m1*60)+(s1));
segundos += ((h2*3600)+(m2*60)+(s2));
}else{
// Tiempo 2 - Tiempo 1
segundos = ((h2*3600)+(m2*60)+(s2)) - ((h1*3600)+(m1*60)+(s1));
}
printf("%ld",segundos);
return 0;
}
Aside from there already existing classes to handle this, here is a solution idea with explanation.
First of all, sec, sec2, min, min2... this is a list of different variables. If you have such a long list, this is a sign that something is amiss. This is C++, so use OOP. That is, use classes.
One header for such a class could be
class Time {
private:
unsigned char seconds;
unsigned char minutes;
unsigned char hours;
public:
Time(const unsigned char _seconds, const unsigned char _minutes,
const unsigned char __hours);
Time(const unsigned int _seconds);
Time difference(const Time& other) const;
unsigned int to_total_seconds() const;
}
This is a far cleaner approach - you don't need all the code right where you use it. Implementations:
Time Time::difference(const Time& other) const {
int difference_seconds = (int) this.to_total_seconds() - (int) other.to_total_seconds();
return Time((unsigned int) std::abs(difference_seconds));
}
unsigned int Time::to_total_seconds() const{
return seconds + 60.*minutes + 60*60*hours;
}
Time::Time(const unsigned int _seconds){
seconds = _seconds % (60*60);
minutes = (_seconds / 60) % 60;
hours = _seconds / (60*60);
}
Time::Time(const unsigned char _seconds, const unsigned char _minutes,
const unsigned char __hours) :
seconds(_seconds), minutes(_minutes), hours(_hours) {
assert(seconds < 60);
assert(minutes < 60);
}
Another approach would be to directly store the total seconds.
I mean, you could do things like doing actual subtractions, like doing difference 6:12 to 4:50 by subtracting 50 from 12 in minutes, resulting in 38 with a remainder, then 6 minus (4 + remainder) = 1 -> 1:38 difference. But why do that when you can simply subtract the seconds and take their absolute value?
But more importantly, keep your main clean. Large procedural code is a clear sign that a class is missing.
(Of course you'll have to add something to the code that gets the values out, preferably a printer. Since there are possibilities for inconsistence, public members are not recommended here.)
Try using std::chrono
void calcDiff(int h1, int m1, int s1, int h2, int m2, int s2){
std::chrono::seconds d = std::chrono::hours(h2-h1)
+ std::chrono::minutes(m2-m1)
+ std::chrono::seconds(s2-s1);
std::cout << std::chrono::duration_cast<std::chrono::hours>(d).count() << "h" <<
std::chrono::duration_cast<std::chrono::minutes>(d % std::chrono::hours(1)).count() << "m" <<
std::chrono::duration_cast<std::chrono::seconds>(d % std::chrono::minutes(1)).count() << "s" << std::endl;
}
int main(){
calcDiff(13, 30, 45, 18, 40, 20); // 5h9m35s
calcDiff(20, 30, 45, 18, 40, 20); // -1h-50m-25s
return 0;
}
The negative result might be a little wierd, but i am sure you can make it work whatever way you want.
I decided to go with converting the minutes and hours to seconds and work the difference for the time periods through a void function I called CalcDiff. I used three referenced variables, FinSec, FinMin and FinHr to store the differences after converting the new DiffSec to the new values.
My program for the void statement is:
void CalcDiff(int seconds, int seconds2, int minutes, int minutes2, int
hour, int hour2, int& FinSec, int& FinMin, int& FinHr)
{
int TotalSec1, TotalSec2, DiffSec, tempMin;
TotalSec1= (hour*3600)+(minutes*60)+seconds;
TotalSec2= (hour2*3600)+(minutes2*60)+seconds2;
if(TotalSec1>TotalSec2)
DiffSec = TotalSec1 - TotalSec2;
else
DiffSec = TotalSec2 - TotalSec1;
FinSec = DiffSec%60;
tempMin = DiffSec/60;
FinMin = tempMin%60;
FinHr = FinMin/60;
}
first of all the syntax of function call should be
CalcDiff( sec, sec2, min, min2, hr, hr2);
instead of
CalcDiff(int sec, int sec2, int min, int min2, int hr, int hr2,
diff);
in the main section
function definition the code should be
void CalcDiff(int seconds, int seconds2, int minutes, int minutes2, int
hour, int hour2, diff)
{
\\ write the code for subtraction here
}
Related
This question already has answers here:
Converting seconds to hours and minutes and seconds
(11 answers)
Closed 9 months ago.
I am trying to solve a problem where I have a total seconds variable, from which I am trying to determine the hours, minutes and seconds.
I do not want to use any external libraries for this task.
What I have noticed is that my seconds variable seems to result in 1 less than the actual value when it is in int form,
but when it is in double form the answer is correct. Why is this?
I would welcome a different approach, perhaps using the remainder operator.
// Example program
#include <iostream>
#include <string>
int main()
{
int total_seconds;
total_seconds = 3870;
int hours, minutes, seconds;
double total_h, total_m, total_s;
int total_hours_int, total_minutes_int;
total_h = (double)total_seconds / 3600;
total_hours_int = total_seconds / 3600;
hours = total_hours_int;
total_m = (total_h - total_hours_int) * 60;
total_minutes_int = (total_h - total_hours_int) * 60;
minutes = total_minutes_int;
total_s = ((double)total_m - total_minutes_int) * 60;
seconds = ((double)total_m - total_minutes_int) * 60;
//seconds = (double)total_s;
std:: cout << hours;
std:: cout << minutes;
std:: cout << total_s;
std:: cout << seconds;
}
Output : 143029
Update:
The answer below was given before the C++98 tag was added to the question.
The chono library is available since C++11, so you can use it only from that version onwards.
You haven't given any context for this task.
My asnwer below assumes you need to solve the problem in any valid C++ manner (i.e. that it is not mandatory the caculate the numbers "by hand").
If this is the case, you can use the C++ chrono library for that, as shown below. This solution is shorter and less error-prone, and avoids the type issues you had altogether.
The main class I used is std::chrono::duration and it's helper types (as you can see in the link), as well as std::chrono::duration_cast.
#include <iostream>
#include <chrono>
int main()
{
int total_seconds = 3870;
std::chrono::seconds total_secs(total_seconds);
auto hours = std::chrono::duration_cast<std::chrono::hours>(total_secs);
auto mins = std::chrono::duration_cast<std::chrono::minutes>(total_secs - hours);
auto secs = std::chrono::duration_cast<std::chrono::seconds>(total_secs - hours - mins);
std::cout << "totals seconds: " << total_secs.count() << std::endl;
std::cout << " hours: " << hours.count() << std::endl;
std::cout << " minutes: " << mins.count() << std::endl;
std::cout << " seconds: " << secs.count() << std::endl;
}
Output:
totals seconds: 3870
hours: 1
minutes: 4
seconds: 30
I've reopened answear since it was updated to C++98.
Before C++11 it can be done nicely using standard library:
#include <iostream>
#include <string>
#include <ctime>
int main()
{
int seconds;
while (std::cin >> seconds) {
std::tm t = {};
t.tm_sec = seconds;
t.tm_mday = 1;
mktime(&t);
t.tm_hour += t.tm_yday * 24;
char buf[32];
strftime(buf, sizeof(buf), "%H:%M:%S", &t);
std::cout << t.tm_yday << ' ' << seconds << " = " << buf << '\n';
}
return 0;
}
https://godbolt.org/z/ceWWfoP6P
im tasked with taking a users inputted start and stop times, and compute and display the difference. We need a header file MyTime that contains the structure with hours, minutes, and seconds. My main function prompts the user to input the time and it goes directly into the MyTime Structure. Then, DetermineElapsedTime function is called and passed two pointers to the two structures containing the user entered times, Then store the pointer it returns in a type "Pointer to MyTime" Variable. That is where im having the trouble. A hint is given as well for this: "Declare a static MyTime structure in DetermineElapsedTime, store the elapsed time in it, then return its address. Returning a pointer or reference to an automatic object is always wrong".
Any Help is greatly appreciated; what i have so far is below. Right now my TimeDiff variable that calls the DetermineElapsedTime function is returning garbage. And im not sure if i set up the structures properly. I am new to C++ so any guidance is deeply appreciated. Thanks.
MAIN FUNCTION:
#include <iostream>
#include "C1A7E1_MyTime.h"
using namespace std;
MyTime* DetermineElapsedTime(const MyTime* StartTime, const MyTime* StopTime);
int main()
{
MyTime StartTime, StopTime;
MyTime *TimeDiff;
for (int i = 1; i <= 3; i++);
{
cout << "Please enter a Start and Stop Time that is space seperated on "
"the same line in the following colon-delimited format "
"(HH:MM:SS): ";
// Declare Colon delimiters
char Colon1, Colon2, Colon3, Colon4;
// Get users input
cin >> StartTime.hours >> Colon1 >> StartTime.minutes >> Colon2
>> StartTime.seconds >> StopTime.hours >> Colon3
>> StopTime.minutes >> Colon4 >> StopTime.seconds;
TimeDiff = DetermineElapsedTime(&StartTime, &StopTime);
cout << "\nThe time elapsed from " << StartTime.hours << Colon1
<< StartTime.minutes << Colon2 << StartTime.seconds << " to "
<< StopTime.hours << Colon3 << StopTime.minutes
<< Colon4 << StopTime.seconds << " is " << TimeDiff;
}
return 0;
}
DetermineElapsedTime Function:
#include "C1A7E1_MyTime.h"
#define HR_SECONDS 3600;
#define MIN_SECONDS 60;
using namespace std;
MyTime *DetermineElapsedTime(const MyTime *StartTime, const MyTime *StopTime)
{
// Declare static MyTime structure to store elapsed time in
MyTime static ElapsedTime;
// Pull out Start Time in seconds
long int Start_Hr = StartTime->hours * HR_SECONDS;
int Start_Min = StartTime->minutes * MIN_SECONDS;
int Start_Sec = StartTime->seconds;
// Total the number of seconds in start time
int TotalStart = Start_Hr + Start_Min + Start_Sec;
// Pull out Stop Time in seconds
long int Stop_Hr = StopTime->hours * HR_SECONDS;
int Stop_Min = StopTime->minutes * MIN_SECONDS;
int Stop_Sec = StopTime->seconds;
// Total the number of seconds in stop time
int TotalStop = Stop_Hr + Stop_Min + Stop_Sec;
// Find the difference in start/stop time
long int TimeDiff = (TotalStop - TotalStart);
// If stop time is less than start time (new day) then make it positive
if (TimeDiff <= 0)
{
TimeDiff = -TimeDiff;
}
// Find time difference in hours
int ElapsedHr = TimeDiff / HR_SECONDS;
ElapsedTime.hours = ElapsedHr;
// Find time difference in minutes
int FirstSub = ElapsedHr * HR_SECONDS;
int remainingSeconds = (TimeDiff) - FirstSub;
int ElapsedMin = remainingSeconds / MIN_SECONDS;
ElapsedTime.minutes = ElapsedMin;
// Find time difference in seconds
int SecondSub = ElapsedMin * MIN_SECONDS;
remainingSeconds = remainingSeconds - SecondSub;
int ElapsedSec = remainingSeconds;
ElapsedTime.seconds = ElapsedSec;
//Return address of elapsed time
return(&ElapsedTime);
}
MyTime Structure / Header File
#ifndef C1A7E1_MYTIME_H // Header Guard
#define C1A7E1_MYTIME_H
//Structure Definition and declaration of structur variables
struct MyTime
{
int hours, minutes, seconds;
};
#endif
I want to write a timer program which shows the time from x seconds to 0 seconds, for example, if x=10s: 10s - 9s - 8s ... 1s. Yet, I want to erase the previous time each second: when the program writes "9s" in cout I want to erase "10s". Do you know how to erase the previous line wrote in std::cout ? I'm on linux but I'd want the code to be portable if that may be possible.
I tried std::cout << "\r"; but it didn't work, for example, whit a ten seconds timer, the program waits ten seconds and then writes "1s".
Here my code:
#include <iostream>
#include <thread>
#include <chrono>
std::string convert(unsigned short int seconds);
int main()
{
unsigned short int seconds {};
std::cout << "Entrez le temps en secondes du minuteur : ";
std::cin >> seconds;
std::cout << std::endl;
for (unsigned short int i {seconds}; i != 0; i--)
{
std::string time {convert(i)};
std::cout << '\r' << time ;
std::this_thread::sleep_for(std::chrono::milliseconds(1000));
}
return 0;
}
std::string convert(unsigned short int seconds)
{
if (seconds < 60)
return std::to_string(seconds) + "s";
else if (seconds >= 60 && seconds < 3600)
return std::to_string(seconds/60) + "min " + std::to_string(seconds%60) + "s";
else
return std::to_string(seconds/3600) + "h " + std::to_string((seconds%3600)/60) + "min " + std::to_string(seconds%60) + "s";
}
Thank you for your help.
you don't flush your buffer, so you see only the last line, cout could be flushed manually using std::cout.flush(); also you should keep in mind that your code rewrites only the begining of the line, so 10s will be changed to 9ss.
this will help
std::cout << '\r' << time;
std::cout.flush();
So I'm trying to make a program that takes some random number of entered seconds and converts it to Days, Hours, Minutes, and Seconds. I had to use symbolic constants to define the hours in a day, minutes in an hour, and seconds in a minute. I passed the value through but it's not being recieved so I end up with some huge negative number. Here's the code. If anyone can tell me where the problem lies I would be ever thankful.
I used the random bit of code in the function definitions code to oput total seconds to see if it was being recieved and it's not.
#ifndef SECONDS_H_
#define SECONDS_H_
#define HOURS_IN_DAY 24
#define MINUTES_IN_HOUR 60
#define SECONDS_IN_MINUTES 60
#include <iostream>
using namespace std;
class Seconds
{
private:
long totalSeconds;
public:
Seconds();
~Seconds(){};
Seconds(int totalSeconds);
void Seconds::convertSeconds(int &days, int &hours, int &minutes, int &seconds);
};
#endif
...
#include <conio.h>
#include <string>
#include <iostream>
#include "seconds.h"
#define HOURS_IN_DAY 24
#define MINUTES_IN_HOUR 60
#define SECONDS_IN_MINUTE 60
Seconds::Seconds(int totalSeconds)
{
totalSeconds = totalSeconds;
}
void Seconds::convertSeconds(int &days, int &hours, int &minutes, int &seconds)
{
cout << endl;
cout << "Total Seconds: " << totalSeconds;
cout << endl;
days = totalSeconds / MINUTES_IN_HOUR / SECONDS_IN_MINUTE / HOURS_IN_DAY;
hours = (totalSeconds / MINUTES_IN_HOUR / SECONDS_IN_MINUTE) % HOURS_IN_DAY;
minutes = (totalSeconds / MINUTES_IN_HOUR) % SECONDS_IN_MINUTE;
seconds = (totalSeconds % SECONDS_IN_MINUTE);
}
...
#include <iostream>
#include <conio.h>
#include <string>
#include "seconds.h"
#define HOURS_IN_DAY 24
#define MINUTES_IN_HOUR 60
#define SECONDS_IN_MINUTES 60
using namespace std;
int main ()
{
int totalSeconds;
int days = 0, hours = 0, minutes = 0, seconds = 0;
cout << "Enter a random massive amount of seconds: ";
cin >> totalSeconds;
Seconds sec(totalSeconds);
sec.convertSeconds(days, hours, minutes, seconds);
cout << "That is equivalent to " << days << " days, " << hours << " hours, " << minutes << " minutes, " << seconds << " seconds." << endl;
cout << "Press any key to continue...";
cin.sync();
_getch();
return 0;
}
This is a problem:
Seconds::Seconds(int totalSeconds)
{
totalSeconds = totalSeconds;
}
The function parameter totalSeconds shadows the class member, so this code is like doing x = x;, it has no effect on this->totalSeconds.
To fix this either use different variable name, or preferably use constructor initialization syntax:
Seconds::Seconds(long totalSeconds)
: totalSeconds(totalSeconds)
{
}
In this version, shadowing does not occur because the constructor initialization lists are smart.
Have you considered that the problem might be Integer Overflow?
i'm not sure why i cant get diff values for my variables here, help!
int main()
{
srand(time(NULL));
srand48(time(NULL));
Packet* firstPacket = new Packet();
firstPacket->packetSize = randSize();
firstPacket->dest = randDest();
firstPacket->arrivalTime = myExp(lamb);
Host[firstPacket->dest].Frame.push_back(firstPacket); // adding first packet
Host[firstPacket->dest].numOfPack++;
calcFrameSize(Host[firstPacket->dest]);
cout << Host[token].frameTVTime << " " << Host[token].frameSize
<< " " << token << " " << curTime << endl;
}
Are your statements:
srand(time(NULL));
srand48(time(NULL));
calling your:
inline float time(int size) { return (10.0*(float)size/12500); }
rather than the system time?
That would explain why you are not getting random numbers.
As pointed out time() is a bad name for that function.
What is in randSize() and randDest()? Make sure that those functions don't call srand() inside.
srand(time(0));
or
#include <sys/time.h>
timeval tim;
gettimeofday(&tim, NULL);
srand((unsigned int) tim.tv_usec);
this is what i have for the other functions.
inline int randSize() { return (rand()%1518 + 64); }
inline int randDest() { return (rand()%10); }
inline float time(int size) { return (10.0*(float)size/12500); }
and this is what i have in the console:
~/152a/2phase$ ./phase2
0 0 1 0.01
0.5752 719 6 0.06
i get those numbers consistently, which i dont think i should be.
thanks.