Jump to content

Recommended Posts

Posted

I have a program where you type in the start and end times of a trip, and supposing that the trip should take 25% less time, it displays the new end time. The new end time is split between hours and minutes in integer form. If the hours has only one digit (or the minutes) then the time will only be in 3 digits (or two if both are only one digit). And this does not work with hhmm military time (the kind I am using).

 

So, simply put, can I get an integer to display always as a two digit number in C++?

 

Tell me if you have no idea what I'm talking about, here's the code:

 

#include <cstdlib>

#include <iostream>

#include <stdio.h>

#include <stdlib.h>

 

using namespace std;

 

int main()

{

string time1;

string hours1;

string minutes1;

 

cout << "Enter start time in standard 24 hour time\n";

cout << "in form hhmm: ";

 

cin >> time1;

hours1 = time1.substr(0,2);

minutes1 = time1.substr(2,2);

 

int ihours1 = atoi((char*)hours1.c_str());

int iminutes1 = atoi((char*)minutes1.c_str());

 

int totalMin1 = ihours1 * 60 + iminutes1;

 

// integer totalmin1 have total minutes for start time

 

string time2;

string hours2;

string minutes2;

 

cout << "Enter end time in standard 24 hour time\n";

cout << "in form hhmm: ";

 

cin >> time2;

hours2 = time2.substr(0,2);

minutes2 = time2.substr(2,2);

 

int ihours2 = atoi((char*)hours2.c_str());

int iminutes2 = atoi((char*)minutes2.c_str());

 

int totalMin2 = ihours2 * 60 + iminutes2;

 

// integer totalmin2 have total minutes for end time

 

double minTimeDiff = totalMin2 - totalMin1;

const double PER = 0.75;

int newMinTimeDiff = minTimeDiff * PER;

int newMinEndTime = totalMin1 + newMinTimeDiff;

 

int newHHEndTime = newMinEndTime / 60;

int newMMEndTime = newMinEndTime % 60;

 

cout << "The new end time is: ";

cout << newHHEndTime << newMMEndTime << endl;

 

system("PAUSE");

return EXIT_SUCCESS;

}

 

 

EDIT: You know what happens when no one responds... I'll figure it out eventually. You can use cout.fill('0') and setw() to do this.

Posted

std::cout TwoDigitInt(int i) {
if (i<10) return std::cout<<"0"<<i
else return std::cout<<i;
}
.
.
.
std::cout<<"The new time is"<< TwoDigitInt(newHHEndTime << newMMEndTime<<std::endl;

I´d try something like that, but I´m not familiar with the std stuff so don´t pin me of the correctness of the syntax.

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now
×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.