Friday, April 16, 2010

C++ exercises: DaysOfWeek


Q: Consider the enumerated type
   enum DaysOfWeek {Sun, Mon, Tues, Web, Thurs, Fri, Sat};
Write a function
   void  GetDay(DaysOfWeek& day);
that reads the name of a day from the keyboard as a string and assigns the corresponding enum value to day. Also write a function
   void PutDay(DaysOfWeek day)
that writes the enum value to the screen. Develop a main program to test the two functions.

#include <iostream>
#include <string>
                                                                                
using namespace std;
                                                                                
enum DaysOfWeek {Sun, Mon, Tues, Wed, Thurs, Fri, Sat};
                                                                                
void GetDay(DaysOfWeek& day)
{
   string s;
                                                                                
   cout << "Input a day: ";
   cin >> s;
                                                                                
   if ("Sunday" == s)
      day = Sun;
   else if ("Monday" == s)
      day = Mon;
   else if ("Tuesday" == s)
      day = Tues;
   else if (s.find("Wed") == 0)
      day = Wed;
   else if (s.find("Thu") == 0)
      day = Thurs;
   else if (s.find("Fri") == 0)
      day = Fri;
   else if (s.find("Sat") == 0)
      day = Sat;
   else
      exit(-1);
}
 
void PutDay(DaysOfWeek day)
{
   cout << "Day: " << day << endl;
}
 
int main()
{
   while (1)
   {
      DaysOfWeek day;
      GetDay(day);
      PutDay(day);
   }

   return 0;
}

No comments:

 
Get This <