fork download
  1. #include <iostream>
  2. #include <string>
  3.  
  4. struct timestamp {
  5. int hour, min, sec;
  6. };
  7.  
  8.  
  9. // overload handles the prepend-0 issue
  10. std::ostream& operator<<( std::ostream& stream, const timestamp& ts ) {
  11. return stream
  12. << (ts.hour < 10 ? "0" : "") << ts.hour << ":"
  13. << (ts.min < 10 ? "0" : "") << ts.min << ":"
  14. << (ts.sec < 10 ? "0" : "") << ts.sec;
  15. }
  16.  
  17. timestamp modify( const timestamp& ts, const std::string& name ) {
  18. std::cout << name << "'s starting value is: " << ts << "\nWould you like to modify it? [y/n] ";
  19. std::cout.flush();
  20.  
  21. char response;
  22. std::cin >> response;
  23.  
  24. // If no modification; return original
  25. if( !( response == 'y' || response == 'Y' ) )
  26. return ts;
  27.  
  28. int hour, min, sec;
  29.  
  30. hour = min = sec = -1;
  31. while( hour < 0 || hour > 23 ) {
  32. std::cout << "Please enter hour [0-23]: ";
  33. std::cout.flush();
  34. std::cin >> hour;
  35. }
  36.  
  37. while( min < 0 || min > 59 ) {
  38. std::cout << "Please enter minutes [0-59]: ";
  39. std::cout.flush();
  40. std::cin >> min;
  41. }
  42.  
  43. while( sec < 0 || sec > 59 ) {
  44. std::cout << "Please enter seconds [0-59]: ";
  45. std::cout.flush();
  46. std::cin >> sec;
  47. }
  48.  
  49. return timestamp { hour, min, sec };
  50. }
  51.  
  52. int main() {
  53. timestamp t1 { 20, 30, 45 };
  54. timestamp t2 { 19, 25, 55 };
  55.  
  56. t1 = modify( t1, "Time1" );
  57. t2 = modify( t2, "Time2" );
  58.  
  59. std::cout << "Modified:\n" << t1 << "\n" << t2 << std::endl;
  60. }
Success #stdin #stdout 0s 3436KB
stdin
Standard input is empty
stdout
Time1's starting value is: 20:30:45
Would you like to modify it? [y/n] Time2's starting value is: 19:25:55
Would you like to modify it? [y/n] Modified:
20:30:45
19:25:55