Home > Mobile >  How do I output two zeros for converting Military Time to standard time?
How do I output two zeros for converting Military Time to standard time?

Time:09-28

I'm trying to make a program to convert military time to standard time, am just having a problem outputting two zeroes for times such as 1300/1:00pm, it outputs as 1:0pm

    int mtime, mins, hrs;
    
        cout<<"Military to Standard Time"<<endl<<"Enter time: ";
        cin>>mtime;
        
        if (mtime >= 0 && mtime <= 2400)
            {
                if (mtime >= 1200)
                {
                    mtime = mtime - 1200;
                    hrs = mtime / 100;
                    mins = mtime % 100;
                    cout<<hrs<<":"<<mins<<" P.M.";
            
                }
                else
                    hrs = mtime / 100;
                    mins = mtime % 100;
                    cout<<hrs<<":"<<mins<<" A.M.";
            }
            
        else
        cout<<"Error, Please Enter Military Time 0000-2400"<<endl;

CodePudding user response:

First, the data is wrong.

Second, if you want to cout 03 rather than 3, you can use

/*
*setw(2):The out put data with is 2 position
*setfill('0'):If the data is not enough 2 position, such 3 is only 1 position,
*             so will fill the output data by zero
*/
cout<<setfill('0')<<setw(2)<<mins;

CodePudding user response:

One solution is to conditionally print a 0 if the minutes is less than 10:

#include <iostream>

int main()
{
   int hrs = 1;
   int mins = 3;
   std::cout << hrs << ":" << (mins<10?"0":"") << mins << " A.M.\n";
   mins = 15;
   std::cout << hrs << ":" << (mins<10?"0":"") << mins << " A.M.\n";
}

Output:

1:03 A.M.
1:15 A.M.

CodePudding user response:

Add curly braces to both the else blocks. Kindly avoid such basic Syntax errors.

           else {
                  hrs = mtime / 100;
                  mins = mtime % 100;
                  cout<<hrs<<":"<<mins<<" A.M.";
                  }

 else {
        cout<<"Error, Please Enter Military Time 0000-2400<<endl;"
         }
  •  Tags:  
  • c
  • Related