Answer to Question #289154 in C++ for amna

Question #289154

Create a time class that includes integer member values for hours, minutes, and seconds. Make a member function get_time() that gets a time value from the user, and a function put_time() that displays a time in 12:59:59 format. Add error checking to the get_time() function to minimize user mistakes. This function should request hours, minutes, and seconds separately, and check each one for ios error status flags and the correct range. Hours should be between 0 and 23, and minutes and seconds between 0 and 59. Don’t input these values as strings and then convert them; read them directly as integers. This implies that you won’t be able to screen out entries with superfluous decimal points, as does the ENGL_IO program in this chapter 12, but we’ll assume that’s not important. In main(), use a loop to repeatedly get a time value from the user with get_time() and then display it with put_time(), like this:

Enter hours: 11

Enter minutes: 59

Enter seconds: 59

time = 11:59:59




1
Expert's answer
2022-01-20T08:27:51-0500
#include <iostream>
#include <iomanip>

using namespace std;

class Time
{
   private:
       int hours;
       int minutes;
       int seconds;
   public:
       int get_time();
       void put_time();
};

int Time::get_time()
{
   cout << "Enter hours: ";
   cin >> hours;
   if ( std::cin.fail() ) {
       cout << "Error entering hours\n";
       cin.clear();
       cin.ignore();
       return -1;
   }
   if (hours < 0 || hours > 23) {
       cout << "Incorrect hours value\n";
       return -1;
   }

   cout << "Enter minutes: ";
   cin >> minutes;
   if ( std::cin.fail() ) {
       cout << "Error entering minutes\n";
       cin.clear();
       cin.ignore();
       return -1;
   }
   if (minutes < 0 || minutes > 59) {
       cout << "Incorrect minutes value\n";
       return -1;
   }

   cout << "Enter seconds: ";
   cin >> seconds;
   if ( std::cin.fail() ) {
       cout << "Error entering seconds\n";
       cin.clear();
       cin.ignore();
       return -1;
   }
   if (seconds < 0 || seconds > 59) {
       cout << "Incorrect seconds value\n";
       return -1;
   }
   return 0;
}

void Time::put_time()
{
   cout << setfill('0') << setw(2) << hours << ":"
        << setfill('0') << setw(2)<< minutes << ":"
        << setfill('0') << setw(2) << seconds << endl;
}

int main()
{
   Time t;
   int res;

   while(1) {
       if (t.get_time() == 0) {
           t.put_time();
       }
   }

   return 0;
}

Need a fast expert's response?

Submit order

and get a quick answer at the best price

for any assignment or question with DETAILED EXPLANATIONS!

Comments

No comments. Be the first!

Leave a comment

LATEST TUTORIALS
New on Blog