01: #include <iostream>
02: #include <sstream>
04: using namespace std;
05: 
06: /** 
07:    Converts an integer value to a string, e.g. 3 -> "3".
08:    @param s an integer value
09:    @return the equivalent string
10: */   
11: string int_to_string(int n) 12: { ostringstream outstr; 14: outstr << n; 15: return outstr.str(); 16: } 18: /** 19: Reads a time from standard input in the format hh:mm or 20: hh:mm am or hh:mm pm 21: @param hours filled with the hours 22: @param minutes filled with the minutes 23: */ 24: void read_time(int& hours, int& minutes) 25: { string line; 27: getline(cin, line); 28: istringstream instr(line); 29: 30: instr >> hours; 32: minutes = 0; 33: 34: char ch; 35: instr.get(ch); 37: if (ch == ':') instr >> minutes; 39: else instr.unget(); 41: /* 42: use 43: instr.putback(ch); 44: if your compiler doesn't support the ANSI unget function 45: */ 46: 47: string suffix; 48: instr >> suffix; 49: 50: if (suffix == "pm") hours = hours + 12; 52: } 54: /** 55: Computes a string representing a time. 56: @param hours the hours (0...23) 57: @param minutes the minutes (0...59) 58: @param military true for military format, 59: false for am/pm format, 60: */ 61: string time_to_string(int hours, int minutes, bool military) 62: { string suffix; 64: if (!military) 65: { if (hours < 12) suffix = "am"; 67: else
68: { suffix = "pm"; 69: hours = hours - 12; 70: } 71: if (hours == 0) hours = 12; 72: } 73: string result = int_to_string(hours) + ":"; 74: if (minutes < 10) result = result + "0"; 75: result = result + int_to_string(minutes); 76: if (!military) result = result + " " + suffix; 78: return result; 79: } 80: 81: int main() 82: { cout << "Please enter the time: "; 84: 85: int hours; 86: int minutes; 87: 88: read_time(hours, minutes); 89: 90: cout << "Military time: "
91: << time_to_string(hours, minutes, true) << "\n"; 92: cout << "Using am/pm: "
93: << time_to_string(hours, minutes, false) << "\n"; 94: 95: return 0; 96: }