#include <iostream>
#include <string>
#include <sstream>
using namespace std;
class TimeUnit
{
public:
TimeUnit(int m, int s)
{
this -> minutes = m;
this -> seconds = s;
}
string ToString()
{
ostringstream o;
o << minutes << " minutes and " << seconds << " seconds." << endl;
return o.str();
}
void Simplify()
{
if (seconds >= 60)
{
minutes += seconds / 60;
seconds %= 60;
}
}
TimeUnit Add(TimeUnit t2)
{
TimeUnit t3;
t3.seconds = seconds + t2.seconds;
if(t3.seconds >= 60)
{
t2.minutes += 1;
t3.seconds -= 60;
}
t3.minutes = minutes + t2.minutes;
return t3;
}
private:
int minutes;
int seconds;
};
int main(){
cout << "Hello World!" << endl;
TimeUnit t1(2,30);
cout << "Time1:" << t1.ToString() << endl;
TimeUnit t2(3,119);
cout << "Time2:" << t2.ToString();
t2.Simplify();
cout << " simplified: " << t2.ToString() << endl;
cout << "Added: " << t1.Add(t2).ToString() << endl;
//cout << " t1 + t2: " << (t1 + t2).ToString() << endl;
/*cout << "Postfix increment: " << (t2++).ToString() << endl;
cout << "After Postfix increment: " << t2.ToString() << endl;
++t2;
cout << "Prefix increment: " << t2.ToString() << endl;*/
}
I'm having problems with my Add method. Xcode is giving me this error: "No matching constructor for initialization of TimeUnit"
Could someone please tell me what I am doing wrong? I've literally tried everything that I know how to do, but I can't even get it to compile with this method.
Here are the instructions from my professor:
The TimeUnit class should be able to hold a time consisting of Minutes
and Seconds. It should have the following methods:
A constructor that takes a Minute and Second as parameters ToString()
- Should return the string equivilant of the time. "M minutes S seconds." Test1 Simplify() - This method should take the time and
simplify it. If the seconds is 60 seconds or over, it should reduce
the seconds down to below 60 and increase the minutes. For example, 2
Min 121 seconds should become 4 minutes 1 second. Test2 Add(t2) -
Should return a new time that is the simplified addition of the two
times Test3 operator + should do the same thing as Add Test4 pre and
postfix ++: should increase the time by 1 second and simplify Test5
In your TimeUnit::Add function, you tried to initialize t3 with default constructor. However, your TimeUnit doesn't have one:
TimeUnit Add(TimeUnit t2)
{
TimeUnit t3; ///<<<---- here
///.....
}
Try update TimeUnit::Add to this way:
TimeUnit Add(const TimeUnit& t2)
{
return TimeUnit(this->minutes+t2.minutes, this->seconds+t2.seconds);
}
The specific problem is because there is no TimeUnit::TimeUnit() defined, only TimeUnit(const int &m, const int &s).
Related
I am trying to make a text game where there is a timer and once the game was finished before or in 60 seconds, there is a bonus points. However, I have no idea how can I get the value or the time from using the chrono without cout-ing it. I want to use the value for calculating the bonus point. i can cout the value through the .count() but I cannot get that value to use for the condition part.
here's my code for the scoring part:
void Game::score(auto start, auto end) {
int bonus = 0;
int total = 0;
string name;
box();
gotoxy(10,8); cout << "C O N G R A T U L A T I O N S";
gotoxy(15,10); cout << "You have successfully accomplished all the levels!";
gotoxy(15,11); cout << "You are now a certified C-O-N-N-E-C-T-o-r-I-s-T" << char(002) << char(001);
gotoxy(20,13); cout << "= = = = = = = = = = GAME STATS = = = = = = = = = =";
gotoxy(25,15); cout << "Time Taken: " << chrono::duration_cast<chrono::seconds>(end - start).count() << " seconds";
gotoxy(25,16); cout << "Points: " << pts << " points";
if (chrono::duration_cast<chrono::seconds>(end - start).count() <= 60) {
bonus == 5000;
} else if (chrono::duration_cast<chrono::seconds>(end - start).count() <= 90) {
bonus == 3000;
} else if (chrono::duration_cast<chrono::seconds>(end - start).count() <= 120) {
bonus == 1000;
}
gotoxy(30,17); cout << "Bonus Points (Time Elapsed): " << bonus;
total = pts + bonus;
gotoxy(25,18); cout << "Total Points: " << total << " points";
gotoxy(20,20); cout << "Enter your name: ";
cin >> name;
scoreB.open("scoreboard.txt",ios::app);
scoreB << name << "\t" << total << "\n";
scoreB.close();
}
You should really use the chrono literals for comparing durations. See example here:
#include <chrono>
#include <iostream>
#include <thread>
using Clock = std::chrono::system_clock;
void compareTimes(std::chrono::time_point<Clock> startTime,
std::chrono::time_point<Clock> finishTime) {
using namespace std::chrono_literals;
std::chrono::duration<float> elapsed = finishTime - startTime;
std::cout << "elapsed = " << elapsed.count() << "\n";
if (elapsed > 10ms) {
std::cout << "over 10ms\n";
}
if (elapsed < 60s) {
std::cout << "under 60s\n";
}
}
int main() {
using namespace std::chrono_literals;
auto startTime = Clock::now();
std::this_thread::sleep_for(20ms);
auto finishTime = Clock::now();
compareTimes(startTime, finishTime);
return 0;
}
Demo: https://godbolt.org/z/hqv58acoY
For this car wash simulation, your program reads in the car arrival time through an input file. The total wash time for a car is 3 minutes. Another car can not go into the wash while a car is being washed which will increase the waiting time. If a car departs at minute 3 the next car needs to go in at minute 4 if it has already arrived.
I have already tried reading in the file all at once and then creating another loop but that has not worked. I have tried many things, I think I am only having a problem with how to loop the program.
#include <iostream>
#include <cassert>
#include <fstream>
#include <queue>
#include <cstdlib>
using namespace std;
class averager {
private:
int cnt;
int sum;
public:
averager(){
cnt=0;
sum=0;
}
void plus_next_number(int value)
{
cnt++;
sum+=value;
}
double average_time()
{
assert(cnt>0);
return (sum/cnt);
}
int how_many_cars()
{
return cnt;
}
};
class Washmachine {
private:
int time_for_wash;
int time_left;
public:
Washmachine(int n) {
time_for_wash = n;
time_left = 0;
}
bool is_busy() {
return (time_left > 0);
}
void startWashing() {
if(!is_busy()) {
time_left = time_for_wash;
}
}
void one_second(){
if(is_busy()) {
--time_left;
}
}
};
int main() {
queue<int> waitQueue;
int carArrival;
averager cal;
ifstream infile;
ofstream arrivalrec;
arrivalrec.open("arrival_time.txt");
arrivalrec << "Car Number " << "Arrival Time " << "Car Wash Start Time " << "Departure Time "
<< "Wait Time "
<< "Total Time " << endl
<< endl;
int maxWaitTime; // maxWaitTime initially 0:00
int totalWaitTime; // total time customers wait
int endTime = 540; // times for the simulation
int totalServiceTime;
int startTime;
int carNum = 0; // number of cars washed in study
int washTime = 3; // fixed time for a wash in minutes
int DeptTime;
int TotalTime;
int timeleft=0;
int waitTime;
int temp;
int sw;
Washmachine carwashing(washTime);
infile.open("input.txt");
for (int startTime=0;startTime<=endTime;startTime++){
infile>>temp;
waitQueue.push(temp);
if((!carwashing.is_busy())&&(!waitQueue.empty())) {
carArrival=waitQueue.front();
waitQueue.pop();
waitTime=temp-carArrival;
cal.plus_next_number(temp-carArrival);
carwashing.startWashing();
}
carwashing.one_second();
if (maxWaitTime<waitTime)
maxWaitTime=waitTime;
// add waiting time for customer to totalWaitTime.
totalWaitTime+=waitTime;
totalServiceTime+=washTime;
startTime=temp+waitTime;
TotalTime=washTime+waitTime;
DeptTime=startTime +washTime;
// increment the number of customers served
carNum++;
// set washAvailable to false since equipment back in service
// output the summary data for the simulation include number of cars
// washed, average customer waiting time and pct of time wash operates
arrivalrec << carNum << " " << temp << " " <<startTime
<< " " << DeptTime << " " <<
waitTime << " " << TotalTime << endl
<< endl << endl;
}
arrivalrec << "Maximum customer waiting time for a car wash is "
<< "14 minutes" << endl;
arrivalrec << "Percentage of time car wash operates is 57 "
//<< ((totalServiceTime / endTime) * 100.0)
<< '%' << endl;
arrivalrec << "Number of customers remaining at " << endTime
<< " is 8"<<endl; //<< waitQueue.size() << endl;
arrivalrec<<"\nCars washed were: "<<carNum<<endl;
arrivalrec<<"\nThe average waiting time is: "<<cal.average_time()<<endl;
int car_denied=0;
while(!waitQueue.empty())
{
waitQueue.pop();
car_denied++;
}
arrivalrec<<"\nThe number of denied cars is: 2 "<<endl;
arrivalrec<<endl;
return 0;
}
Car Arrival 0 car start 0 car depart 3 wait time 0 total time 3
3 4 7 1 4
10 10 13 0 3
11 14 17 3 6
Please try the following loop for the main function of your Car washing simulation.
Instead of looping over startTime, the loop uses the simulation runTime. All events like putting a car to the queue, starting and documenting the car washing process as well as counting waitTime are done by conditions:
infile.open("input.txt");
infile >> temp;
carNum = 1;
for (runTime=1;runTime<=endTime;runTime++){
if (runTime == temp) {
waitQueue.push(temp);
infile >> temp;
}
if((!carwashing.is_busy())&&(!waitQueue.empty())) {
carArrival=waitQueue.front();
waitQueue.pop();
startTime = runTime;
waitTime=startTime-carArrival;
totalWaitTime = waitTime;
TotalTime = washTime + waitTime;
cal.plus_next_number(startTime-carArrival);
carwashing.startWashing();
}
else
{
waitTime++;
}
if (carwashing.is_busy())
carwashing.one_second();
if ((!carwashing.is_busy())&&(startTime >= DeptTime)) {
DeptTime = startTime + washTime;
totalServiceTime += washTime;
arrivalrec << carNum << " " << carArrival << " " << startTime
<< " " << DeptTime << " " <<
totalWaitTime << " " << TotalTime << endl
<< endl << endl;
carNum++;
}
}
Please note that the file reading of the first car is done outside of the loop.
I also added the runTime variable and some initialization to your declaration:
queue<int> waitQueue;
int carArrival = 0;
averager cal;
ifstream infile;
ofstream arrivalrec;
arrivalrec.open("arrival_time.txt");
arrivalrec << "Car Number " << "Arrival Time " << "Car Wash Start Time " << "Departure Time "
<< "Wait Time "
<< "Total Time " << endl
<< endl;
int maxWaitTime = 0; // maxWaitTime initially 0:00
int totalWaitTime = 0; // total time customers wait
int endTime = 75; // times for the simulation
int totalServiceTime = 0;
int startTime = 0;
int carNum = 0; // number of cars washed in study
int washTime = 3; // fixed time for a wash in minutes
int DeptTime = 0;
int TotalTime = 0;
int timeleft=0;
int waitTime=0;
int temp;
int sw;
int runTime;
Washmachine carwashing(washTime);
I've taken the desired output from your other post:
Hope it helps you?
I have a program that uses this popular library, however I am struggling to use it to convert from seconds to minutes
The following code...
#include <iostream>
#include "units.h"
int main(int argc, const char * argv[])
{
{
long double one = 1.0;
units::time::second_t seconds;
units::time::minute_t minutes(one);
seconds = minutes;
std::cout << "1 minute is " << seconds << std::endl;
}
{
long double one = 1.0;
units::time::second_t seconds(one);
units::time::minute_t minutes;
minutes = seconds;
std::cout << "1 second is " << minutes << std::endl;
}
return 0;
}
produces...
1 minute is 60 s
1 second is 1 s
however, I would have expected it to produce...
1 minute is 60 s
1 second is .016666667 m
The library offers a units::convert method, check the doc here.
Here's a working snippet:
long double one = 1.0;
units::time::second_t seconds(one);
units::time::minute_t minutes;
minutes = seconds;
std::cout << "1 second is " << minutes << std::endl;
std::cout << "1 second is "
<< units::convert<units::time::seconds, units::time::minutes>(seconds)
<< std::endl;
For more, I suggest searching in the doc.
I don't know the library you are using, but C++11 added the std::chrono::duration class that seems to be able to do what you want:
#include <chrono>
#include <iostream>
int main()
{
{
std::chrono::minutes minutes(1);
std::chrono::seconds seconds;
seconds = minutes;
std::cout << "1 minute is " << seconds.count() << std::endl;
}
{
std::chrono::seconds seconds(1);
using fMinutes = std::chrono::duration<float, std::chrono::minutes::period>;
fMinutes minutes = seconds;
std::cout << "1 second is " << minutes.count() << std::endl;
}
return 0;
}
Note that the default std::chrono::minutes uses an integer counter, and thus reports that 1 second is 0 minutes. That is why I define my own float-minutes.
In any case, the above program produces the following output:
1 minute is 60
1 second is 0.0166667
I'm trying to learn how classes and their constructors work by creating a Time class that includes an hour, minute, and second. I wanted to print one time by using the default constructor and one through user input. While my program compiles, it does not ask for user input, most likely because of the way I call the class function getHour (if I were to only print the input hour). I am also unsure of how to print the time (0,0,0) through the default constructor.
Any help would be appreciated!
Main:
#include <iostream>
#include "Time.h"
int main(){
std::cout << "Enter the hour, minute, and second: " << std::endl;
int hour, minute, second;
std::cin >> hour >> minute >> second;
Time time1(hour, minute, second);
std::cout << time1.getHour() << std::endl;
return 0;
}
Class implementation:
#include <iostream>
#include "Time.h"
//default constructor
Time::Time() {
hour = 0;
minute = 0;
second = 0;
}
//construct from hour, minute, second
Time::Time(int theHour, int theMinute, int theSecond) {
hour = theHour;
minute = theMinute;
second = theSecond;
}
int Time::getHour() const {
return hour;
}
int Time::getMinute() const {
return minute;
}
int Time::getSecond() const {
return second;
}
Works fine for me, this was my output:
Enter the hour, minute, and second:
2
45
32
2
Press any key to continue . . .
Make sure you are rebuilding the code and running the new executable.
In the constructor you can just do:
Time::Time() {
hour = 0;
minute = 0;
second = 0;
std::cout << hour << " " << minute << " " << second << std::endl;
}
this will be called anytime you call Time with the default constructor:
std::cout << "Enter the hour, minute, and second: " << std::endl;
int hour, minute, second;
std::cin >> hour >> minute >> second;
Time t; //<--- this prints 0,0,0
Time time1(hour, minute, second);
std::cout << time1.getHour() << std::endl;
system("pause");
return 0;
will result in:
Enter the hour, minute, and second:
11
19
59
0 0 0
11
Press any key to continue . . .
I am also unsure of how to print the time (0,0,0) through the default constructor.
Unless I missing something subtle,
// Construct a Time object using the default constructor.
Time time2;
// Print it's hour
std::cout << time2.getHour() << std::endl;
The code you shared doesn't try to print an object constructed with the default constructor since getHour() is called by time1. The is doing what you tell it to do. If you want the full time from time1you'll have to call all of the getters eg: std::cout << time1.getHour() << " : " << time1.getMinute() << " : " << time1.getSecond() << std::endl
"I am also unsure of how to print the time (0,0,0) through the default constructor."
consider a displayTime() method that can be called on to display the time of any instance
int _tmain(int argc, _TCHAR* argv[])
{
std::cout << "Enter the hour, minute, and second: " << std::endl;
int hour, minute, second;
std::cin >> hour >> minute >> second;
Time time1(hour, minute, second); // overloaded constructor
Time time2; // default constructor
// std::cout << time1.getHour() << std::endl;
// std::cout << time2.getHour() << std::endl;
time1.displayTime();
time2.displayTime();
getch();
return 0;
}
add displayTime() method
void Time::displayTime() const{
std::cout << this->hour << ","
<< this->minute << ","
<< this->second << std::endl;
}
I am trying to find the average UTC time of when a function was called. So I do:
boost::posix_time::ptime current_time_before(boost::posix_time::microsec_clock::universal_time());
DoStuff();
boost::posix_time::ptime current_time_after(boost::posix_time::microsec_clock::universal_time());
How do I go about calculating the averages between these two times?
I tried:
double time_avg = (current_time_before+current_time_after)*0.5;
But I get an error on a linux system that seems to have a problem with "+" but not "-" .
Thank you for your help.
Just... write it naturally?
ptime midpoint(ptime const& a, ptime const& b) {
return a + (b-a)/2; // TODO check for special case `b==a`
}
Live demo:
Live On Coliru
#include <boost/date_time/posix_time/posix_time.hpp>
using boost::posix_time::ptime;
ptime midpoint(ptime const& a, ptime const& b) {
return a + (b-a)/2;
}
int main() {
ptime a = boost::posix_time::second_clock::local_time();
ptime b = a + boost::posix_time::hours(3);
std::cout << "Mid of " << a << " and " << b << " is " << midpoint(a,b) << "\n";
std::swap(a,b);
std::cout << "Mid of " << a << " and " << b << " is " << midpoint(a,b) << "\n";
}
Prints
Mid of 2016-Sep-15 11:17:10 and 2016-Sep-15 14:17:10 is 2016-Sep-15 12:47:10
Mid of 2016-Sep-15 14:17:10 and 2016-Sep-15 11:17:10 is 2016-Sep-15 12:47:10