How can I convert military time to regular time. the regular time must be a string

Viewed 79

I hope someone can help me. I keep getting one 0 on the minutes side. for example, for input 0000 I get 12:0 AM or for input 608 I get 6:8 AM. How can I get double 0 on the minutes side?

on main.cc I have:

#include "time_converter.h"
#include <iostream>



int main() {
  int military_time;
  std::cout << "Please enter the time in military time: ";
  std::cin >> military_time;
  
  // TODO: Call your function to convert from military time to regular time
  // and assign its result to regular_time.

std::string regular_time;
regular_time = MilitaryToRegularTime(military_time);


  std::cout << "The equivalent regular time is: " << regular_time << "\n";
  return 0;
}

time_converter.h:

#include <iostream>

// Converts the time in military format to regular format.
std::string MilitaryToRegularTime(int military_time);

time_converter.cc:

#include <iostream>


std::string amorpm;
std::string MilitaryToRegularTime(int military_time) {
  // TODO: convert military_time to regular time in string format.
  // Hint: std::to_string() converts a given integer to a string. 
  
  
   int regular_hr = military_time / 100;
    if (regular_hr >= 13){
       regular_hr = (military_time / 100) - 12;
        }
    
    if (regular_hr == 0){
    regular_hr = 12;
    }
   
   int regular_min = military_time % 100;
    
    if (military_time >= 1200 && military_time <= 2359){
  amorpm = " PM\n";
 
    }
    if (military_time >= 0000 && military_time <= 1159 ){
  amorpm = " AM\n";
    }


   std::string regular_hr_str = std::to_string(regular_hr);
   std::string regular_min_str = std::to_string(regular_min);
 

  return regular_hr_str + ":" + regular_min_str + amorpm;
}
1 Answers

The function std::to_string does not have sufficient formatting options to do what you require.

However, if you instead use an object of type std::ostringstream as the target, you can use the std::setw and std::setfill I/O manipulators to accomplish what you want. You can use std::setw to set the minimum width to 2 and std::setfill to set the fill character to '0'.

After you are finished, you can convert the std::ostringstream object to a std::string using std::ostringstream::str.

#include <iostream>
#include <sstream>
#include <iomanip>

int main()
{
    int hours = 6;
    int minutes = 8;

    std::ostringstream oss;
    std::string str;

    //write desired time to ostringstream object
    oss <<
        "The time is " <<
        std::setw( 2 ) << std::setfill( '0' ) <<
        hours <<
        ":" <<
        std::setw( 2 ) << std::setfill( '0' ) <<
        minutes <<
        ".\n";

    //convert ostringstream to a string
    str = oss.str();

    //print the string
    std::cout << "String content: " << str << '\n';
}

This program has the following output:

String content: The time is 06:08.
Related