leading zeros

I have a simple question. I'm using a class that inputs time (my_time, your_time) in terms of hrs:mins. I've got the whole program figured out except for one little thing -- where the digits are less than ten I need to add a leading zero to it (so 5:1 becomes 05:01).

I would just do a setw and fill the empty spaces with zeros, but I'm not having the hrs and mins entered seperately.

Here is my input (the >> is overloaded):

in main:
 
cin >> your_time;


in class:
1
2
3
4
5
6
7
8
9
void time24::input(istream& fin)
{
  char ch;
  if (&cin == &fin)
  cout << "Enter time in the form 01:23 > ";

  fin >> hrs >> ch >> mins;
  normalize();  
}


and (overloading >>):
1
2
3
4
5
6
7
istream& operator >> (istream& inp, time24& your_time)
{    
   your_time.input(inp);
 
   return(inp);
  
}


Since << is also overloaded, the code for printing is simply:
cout << "Your time is > " << your_time << endl << endl;

Is there any way that I can add leading zeros to the hrs and mins? I tried to make an if statement like:
1
2
3
4
5
6
if (hrs < 10) {
    hrs = 0 + hrs //obviously this would have to be made some sort of string?
}
if (mins < 10) {
    mins = 0 + mins //again, string
}


Any help or advice is greatly appreciated :D

-okapi
You could just use setw() and tell it to fill with '0's.
That was my initial thought too, but that doesn't work if the minutes is less than 10, since the hrs, mins, and colon are all input together.

Any other solutions?

Thanks for the help :)
You could parse out the two, pad them with zeros, and reconstruct the string...
I don't see how leading zeroes on input is a problem. It should work either way as is. Output is your
only problem, and a combination of std::setw( 2 ) and std::setfill( '0' ) should do the trick.
Topic archived. No new replies allowed.