Adding zero with modulus division
A simple question that I cannot solve is putting a zero in front of less than 10 digit number for time.
Example: Turn 327 minutes to hours and minutes
This would become 5:27, 5 hours and 27 minutes
but in the case of 184 minutes it should be 3:04 but output shows 3:4
This is what I have so far
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
|
#include <cstdlib>
#include <iostream>
using namespace std;
int main()
{
int minutes;
cout << "Enter the number of minutes ";
cin >> minutes;
cout <<"This is " << minutes/60 << ":" << minutes%60 << endl;
system("PAUSE");
return (0);
|
Solution #1 - uses manipulator functionality (from <iomanip>)
Note that I'm setting the fill back to the default after using it. setw() auto resets so there is no need to reset the field width.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
|
#include <cstdlib>
#include <iostream>
#include <iomanip>
using namespace std;
int main()
{
int minutes;
cout << "Enter the number of minutes ";
cin >> minutes;
cout << "This is " << minutes/60 << ":" << setfill('0') << setw(2)
<< minutes%60 << setfill(' ') << endl;
system("PAUSE");
return (0);
}
|
Solution #2 - just add an extra '0' explictly when required.
I would prob. use this approach as it avoids dragging in <iomanip> for one lone '0'
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
|
#include <cstdlib>
#include <iostream>
using namespace std;
int main()
{
int minutes;
cout << "Enter the number of minutes ";
cin >> minutes;
cout << "This is " << minutes/60 << ((minutes%60 < 10) ? ":0" : ":")
<< minutes%60 << endl;
system("PAUSE");
return (0);
}
|
Though I'd prob code it more like
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
|
#include <cstdlib>
#include <iostream>
using namespace std;
int main()
{
int minutes;
cout << "Enter the number of minutes ";
cin >> minutes;
int hours = minutes/60;
minutes %= 60;
cout <<"This is " << hours << ((minutes < 10) ? ":0" : ":")
<< minutes << endl;
system("PAUSE");
return (0);
}
|
Last edited on
Topic archived. No new replies allowed.