code.cpp 999 B

12345678910111213141516171819202122232425262728
  1. /* Write a function that receives the time in 12-hour AM/PM format
  2. * and returns a string representation of the time in military (24-hour)
  3. * format.
  4. * Midnight is 12:00:00AM on a 12-hour clock, and 00:00:00 on a 24-hour clock.
  5. * Noon is 12:00:00PM on a 12-hour clock, and 12:00:00 on a 24-hour clock.
  6. */
  7. std::string convertTime(std::string str) {
  8. // create substr of first 2 characters in string
  9. int cCheck = std::stoi (str.substr(0,2));
  10. // if cCheck is 12, set it equal to 0. Now AM or PM will show correctly. URHMHUMPH!!!
  11. if (12 == cCheck){
  12. cCheck = 0;
  13. }
  14. // use the substr for conditional if/else to see if 12 needs to be added
  15. // use AM/PM to see if it needs to be modified.
  16. if(str.substr(8,2)== "PM"){
  17. cCheck += 12;
  18. }
  19. // if cCheck is one digit, add a leading zero
  20. if(cCheck<10){
  21. str.replace(0,2,"0" + std::to_string(cCheck));
  22. }
  23. // otherwise cCheck is a two digit replacement
  24. else {
  25. str.replace(0,2,std::to_string(cCheck));
  26. }
  27. return str.substr(0,8);
  28. }