HiveBrain v1.2.0
Get Started
← Back to all entries
patterncppMinor

Formatting seconds as hours:minutes:seconds

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
hoursformattingsecondsminutes

Problem

This is basically my school homework and I want to know what to improve, and what not to do.
The homework basically is this:
You will get a input in seconds, which is supposed to be shown as H:MM:SS where H is hours M is minutes and S is seconds. The formatting is supposed to look like in my example. ( note: In output, 0s from the left will be ignored and replaced with spaces )

Input:
3000
730
308
3967
15
1

Output:
The count of entires: 6
  50:00
  12:10
   5:08
1:06:07
     15
      1


So basically, I did a code based on the example. I haven't got more informations, just that but it is enough and fun.
Here goes my code:

#include 
#include 

inline int CountSpaces ( int hod, int min, int sec ){
    int spaces = -1;
    // 1:06:07
    if ( hod )
        return 0;
    if ( min >= 10 )
        return 2;
    if ( min  0 )
        return 3;
    if ( sec >= 10 )
        return 5;
    if ( sec  0 ){
        bHour = true;
        std::cout  0 ){
        bMin = true;
        if ( bHour ){
            if ( min  0 )
            std::cout = 0 ){
        if ( sec > num ){
        arr [ count++ ] = num;
    }
    std::cout << "The count of entires: " << count << std::endl;
    for ( int i = 0 ; i < count ; i++ ){

        Write ( arr [ i ] );
    }

    return 0;
}

Solution

-
Bug

Handling a case of 0 minutes is a bit more involved. For example, giving 3601 as an input produces 1:1 instead of expected 1:00:01.

-
Trust your math

min and sec are guaranteed to be less than 60. There is no point to test for it.

-
Computing spaces

I recommend not to compute them explicitly. You know that the output should be right-aligned into the 7-character-wide field. An std::setw(7) manipulator is specifically designed to do the job. Write your output to the string (or a stringstream), and

std::cout << std::setw(7) << s << '\n';


will achieve the goal.

Code Snippets

std::cout << std::setw(7) << s << '\n';

Context

StackExchange Code Review Q#132340, answer score: 7

Revisions (0)

No revisions yet.