I am writing a simple program to simulate a watch. Class Date, Class Time, Class Watch. Watch is derived from Date and Time. Trying to call a date member function from Time member function. It says I cant do it without an object. I am learning and I am sure most of this is crap haha. Any help would be appriciated. Basically at the end of Time::Tick, I am trying to call Class Date member function inDay. Calling one member function from another class member function. I dont know how to do a friend function from another class. I tried to make my functions static but it leads me down a long road of errors. Any advice?
#include <iostream>
#include <iomanip>
#include <windows.h>
using namespace std;
class Date
{
public:
Date();
void inDay();;// increments day, tests if month increments, if true, increment
void inMonth(); // increments month, tests if year increments, if true, increment
void inYear(); // increment year
void displayWatch(); // calls daysInMonthSwith, calls inDay, Display date
int daysInMonthSwitch(); // determines the number of days in the month based on which month using a switch
//void testPrint(); //Testing purposes only
void setDay();
void setMonth();
void setYear();
private:
int day;
int month;
int year;
int daysInMonth;
};
class Time{
public:
Time();
void setTime(int, int, int ); // set hours, minutes, seconds
void printStandard(); // print time in standard time format 12h
void setHour();
void setMin();
void setSec();
void tick();
private:
int hour;
int minute;
int second;
};
class Watch: public Time, public Date {
public:
Watch();
int getDate();
void setTime(int, int, int);
int getTime();
private:
};
//class Time::
Date::Date() : // Class Constructor
day(27),
month(2),
year(2013),
daysInMonth(31)
{
} // End Constructor
void Date::setDay()
{
int tempDay;
cout << "There are " << daysInMonth << " in the current month. Please enter a day between 1 and " << daysInMonth << ": ";
cin >> tempDay;
while (tempDay < 1 || tempDay > daysInMonth)
{
cout << "You entered a day outside the range." << endl;
cout << "There are " << daysInMonth << " in the current month. Please enter a day between 1 and " << daysInMonth << ": ";
cin >> tempDay;
}
day = tempDay;
}
void Date::setMonth()
{
int tempMonth;
cout << "There are 12 in the year. Please enter a day between 1 and 12: ";
cin >> tempMonth;
while (tempMonth < 1 || tempMonth > 12)
{
cout << "You entered a month outside the range." << endl;
cout << "There are 12 in the year. Please enter a day between 1 and 12: ";
cin >> tempMonth;
}
month = tempMonth;
}
void Date::setYear()
{
int tempYear;
cout << "Please enter a year in the full number(Correct: 2005, Incorrect: 05): ";
cin >> tempYear;
year = tempYear;
}
void Date::displayWatch()
{
daysInMonthSwitch();
cout << "Date: " << month << "/" << day << "/" << year << endl;
//testPrint(); // Prints number of days in current month for testing only
//cout << "Month: " << month << endl; // Prints month for testing purposes
//inDay();
}
////////////// inDay function increments day and if conditions are met, increments month and year
void Date::inDay() //increments month and if day is more greater than number of days in month, call inMonth function
{
day++;
if (day > daysInMonth)
{
inMonth();
day = 1;
}
}// end function
void Date::inMonth() // increment month and if month is more greater than or equal to 12, call inYear function
{
month++;
if (month >= 12)
{
Date::inYear();
}
} // end function
void Date::inYear() // increment year
{
year++;
month = 1;
} // end function
//void Date::testPrint()
//{
// cout << "Days in month: " << daysInMonth << endl;
//} // for testing purposes only
int Date::daysInMonthSwitch() // Function contains switch that determines the number of days in the current month
{
//int month = m;
int result;
switch(month)
{
case 1:
result = 31;
break;
case 2:
result = 28;
break;
case 3:
result = 31;
break;
case 4:
result = 30;
break;
case 5:
result = 31;
break;
case 6:
result = 30;
break;
case 7:
result = 31;
break;
case 8:
result = 31;
break;
case 9:
result = 30;
break;
case 10:
result = 31;
break;
case 11:
result = 30;
break;
case 12:
result = 31;
break;
default :
cout << "Invalid Month" << endl;
}
daysInMonth = result;
return daysInMonth;
} // end daysInMonthSwitch function
//////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////
Time::Time()
{
const time_t currentTime = time(0);
const tm *localTime = localtime( ¤tTime );
setTime(localTime->tm_hour, localTime->tm_min, localTime->tm_sec);
}
void Time::setHour()
{
int h;
cout << "Please enter the hour: ";
cin >> h;
hour = ( h >= 0 && h <= 24 ) ? h : 0;
}
void Time::setMin()
{
int m;
cout << "Please enter the minute: ";
cin >> m;
minute = ( m >= 0 && m <= 60 ) ? m : 0;
}
void Time::setSec()
{
int s;
cout << "Please enter the second: ";
cin >> s;
second = ( s >= 0 && s <= 60 ) ? s : 0;
}
void Time::setTime( int h, int m, int s )
{ // validating time time, if incorrent, set to 0
hour = ( h >= 0 && h <= 24 ) ? h : 0;
minute = ( m >= 0 && m <= 60 ) ? m : 0;
second = ( s >= 0 && s <= 60 ) ? s : 0;
}
///void Time::tick();
void Time::printStandard()
{
cout << ((hour == 0 || hour == 12) ? 12 : hour % 12) << ":" <<
setfill('0') << setw(2) << minute << ":" << setw(2) << second
<< ( hour < 12 ? " AM" : " PM");
}
void Time::tick()
{
while (second >=0 && second <=60)
{
if (second < 59)
{
Sleep(1000);
second++;
}
else
{
Sleep(1000);
minute++;
second = 0;
if (minute >= 60)
{
hour++;
minute = 0;
if (hour >= 24)
hour = 0;
inDay();
}
}
}
};
///////////////////////////////////////////////////////////////////
Watch::Watch()
{}
////////////////////////////////////////////////////////////////// End Member Functions
int main()
{
Watch watch1;
watch1.displayWatch();
watch1.printStandard();
system("pause");
watch1.setDay();
watch1.displayWatch();
watch1.printStandard();
system("pause");
watch1.inDay();
watch1.displayWatch();
watch1.printStandard();
system("pause");
return 0;
} // end main
Your class Time does not descend from Date. It can't call methods on classes that might also happen to be parents of child classes. Imagine if you instantiated a Time alone. What Date would it operate on?
A method that increments Time until it rolls over and then increments Date would need to be in Watch where it can see both.
Related
I have an assignment that essentially requires me to use a class to output the day of the week based upon input from the user EX: user enters sat (first three letters) --> output = This day of the week is: 6. We're also required for the program to also ouput the next six days following the day specified by the user, ex:
Input:
tue
Output:
This day of the week is: 2
This day of the week is: 3
This day of the week is: 4
This day of the week is: 5
This day of the week is: 6
This day of the week is: 7
This day of the week is: 1
My program is bit messy as I initially misunderstood the question. I was able to develop a functioning program that allows the user to input a number for the day, but not the first three letters as that part of the code seems not to be functioning whatsoever.
Any suggestions or solutions would be immensely appreciated. Thank you in advance.
#include <iostream>
#include <string>
using namespace std;
//
// Definition of the DayOfWeek class
//
class DayOfWeek
{
public:
DayOfWeek(int dayNum);
// Precondition: The parameter dayNum contains a valid
// day number (1 - 7)
// Postcondition: The member variable day has been set to
// the value of the parameter dayNum.
DayOfWeek();
// Sets the member variable month to 1 (defaults to January).
DayOfWeek(char fL, char sL, char tL);
void outputDayNumber();
// Postcondition: The member variable day has been output
// to the screen if it is valid; otherwise a "not valid"
// message is printed.
void outputDayLetters();
// Postcondition: The first three letters of the name of the
// day has been output to the screen if the day is
// valid (1 - 12); otherwise a message indicating the month
// is not valid is output.
DayOfWeek NextDay();
// Precondition: The month is defined and valid.
// Returns the next day as an object of type Day.
private:
int day;
};
int main()
{
//
// Variable declarations
//
int DayNum;
string DayWord;
char letter1, letter2, letter3; // first 3 letters of the day
char testAgain; // y or n - loop control
//
// Loop to test the next month function
//
do {
cout << endl;
cout << "Enter a day number: ";
cin >> DayNum;
DayOfWeek testDay(DayNum);
cout << endl;
cout << "This day ..." << endl;
testDay.outputDayNumber();
testDay.outputDayLetters();
DayOfWeek next = testDay.NextDay();
cout << endl;
cout << "Next day ..." << endl;
next.outputDayNumber();
next.outputDayLetters();
//
// See if user wants to try another month
//
cout << endl;
cout << "Do you want to test again? (y or n) ";
cin >> testAgain;
} while (testAgain == 'y' || testAgain == 'Y');
return 0;
}
DayOfWeek::DayOfWeek()
{
day = 1;
}
DayOfWeek::DayOfWeek(int dayNum)
{
if (dayNum >= 1 && dayNum <= 7)
day = dayNum;
else {
dayNum = 1;
}
}
void DayOfWeek::outputDayNumber()
{
if (day >= 1 && day <= 7)
cout << "Day: " << day << endl;
else
cout << "Error - The day is not valid!" << endl;
}
void DayOfWeek::outputDayLetters()
{
switch (day)
{
case 1:
cout << "1" << endl;
break;
case 2:
cout << "2" << endl;
break;
case 3:
cout << "3" << endl;
break;
case 4:
cout << "4" << endl;
break;
case 5:
cout << "5" << endl;
break;
case 6:
cout << "6" << endl;
break;
case 7:
cout << "7" << endl;
break;
default:
cout << "Error - the day is not valid!" << endl;
}
}
DayOfWeek::DayOfWeek(char firstL, char secondL, char thirdL)
{
/**
*check to for the first characters or letter of the day
*prints the day based on the characters user input
*check if the characters is valid
*/
if (firstL >= 65 && firstL <= 90) {
firstL += 32;
}
if (secondL >= 65 && secondL <= 90) {
secondL += 32;
}
if (thirdL >= 65 && thirdL <= 90) {
thirdL += 32;
}
if (firstL == 'm' && secondL == 'o' && thirdL == 'n') {
day = 1;
}
else if (firstL == 't' && secondL == 'u' && thirdL == 'e') {
day = 2;
}
else if (firstL == 'w' && secondL == 'e' && thirdL == 'd') {
day = 3;
}
else if (firstL == 't' && secondL == 'h' && thirdL == 'u') {
day = 4;
}
else if (firstL == 'f' && secondL == 'r' && thirdL == 'i') {
day = 5;
}
else if (firstL == 's' && secondL == 'a' && thirdL == 't') {
day = 6;
}
else if (firstL == 's' && secondL == 'u' && thirdL == 'n') {
day = 7;
}
else {
day = 0;
cout << "Invalid Day" << endl;
}
}
DayOfWeek DayOfWeek::NextDay() {
int d = (day % 7) + 1;
return DayOfWeek(d);
}
UPDATE:
Changed my code up entirely but still need to implement the next day and then
the next 6 days function.
NEW CODE :
#include <iostream>
#include <string>
using namespace std;
class DayOfWeek
{
string day;
public:
DayOfWeek();
DayOfWeek(string day_name);
void print_car(ostream& ins);
};
int main() {
string day_name;
cout << "Enter the first three letters of the day :" << endl;
cin >> day_name;
DayOfWeek my_car(day_name);
my_car.print_car(cout);
return 0;
}
DayOfWeek::DayOfWeek(string day_name) {
day = day_name;
}
void DayOfWeek::print_car(ostream& outs) {
if (day == "Mon" || day == "mon") {
outs << "This is day 1 of the week" << endl;
}
if (day == "Tue" || day == "tue") {
outs << "This is day 2 of the week" << endl;
}
if (day == "Wed" || day == "wed") {
outs << "This is day 3 of the week" << endl;
}
if (day == "Thu" || day == "thu") {
outs << "This is day 4 of the week" << endl;
}
if (day == "Fri" || day == "fri") {
outs << "This is day 5 of the week" << endl;
}
if (day == "Sat" || day == "sat") {
outs << "This is day 6 of the week" << endl;
}
if (day == "Sun" || day == "sun") {
outs << "This is day 7 of the week" << endl;
}
}
Final Update:
I am nearly at a final solution but I am having a issues declaring a
new object for the final part of my problem.
The code is here...
#include <iostream>
#include <string>
using namespace std;
class DayOfWeek
{
string day;
// int nday;
public:
DayOfWeek();
DayOfWeek(string day_name);
void print_day(ostream& ins);
};
int main() {
string day_name;
int nday;
cout << "Enter the first three letters of the day :" << endl;
cin >> day_name;
DayOfWeek week_day(day_name);
week_day.print_day(cout);
DayOfWeek next_day;
int d = _____;
int current = (d % 7) + 1;
int count = 0;
while (count < 7) {
next_day = DayOfWeek(current);
next_day.print_day(cout);
count++;
}
return 0;
}
DayOfWeek::DayOfWeek(string day_name) {
day = day_name;
}
void DayOfWeek::print_day(ostream& outs) {
int dayNumber = 0;
if (day == "Mon" || day == "mon") {
dayNumber = 1;
}
if (day == "Tue" || day == "tue") {
dayNumber = 2;
}
if (day == "Wed" || day == "wed") {
dayNumber = 3;
}
if (day == "Thu" || day == "thu") {
dayNumber = 4;
}
if (day == "Fri" || day == "fri") {
dayNumber = 5;
}
if (day == "Sat" || day == "sat") {
dayNumber = 6;
}
if (day == "Sun" || day == "sun") {
dayNumber = 7;
}
outs << "This is day " << dayNumber << " of the week." << endl;
}
I have some issue being able to convert the user inputted name of the day, into an integer that I can use to plug into the next_day function.
I am also having an error in the while loop
while (count < 7) {
next_day = DayOfWeek(current);
next_day.print_day(cout);
count++;
}
specifically line:
next_day = DayOfWeek(current);
The error says that there's no instance of DayOfWeek::DayOfWeek matching the argument list.
I feel like I'm nearly there if not for these couple of bumps.
Code below should do some of what you need.
Instead of using chars, I've used a string. That way you can compare the whole string in one go rather than 1 char at a time.
Also for comparing the input against the day-words, i have created an array of Strings. The index corresponds to the day, i.e 0=sunday, 1=monday etc.
This is neat for 2 reasons, we can compare with a loop easily, and as soon as we find the matching day, we just grab the index and there we have our day number. Store that number, and then we can return that for the day number, or use the day as an index in the array to return the day word instead.
Hopefully this is clear, you still need to make a function to return the next day, but the 3 letter input should work.
#include <iostream>
#include <cctype> // std::tolower
#include <algorithm> // std::transform
class DayOfWeek
{
private:
const static std::string days[7];
private:
int day;
public:
DayOfWeek();
DayOfWeek(int);
DayOfWeek(std::string);
void outputDayNumber();
void outputDayLetters();
};
// if we have an array of strings, we can use these for comparison and also Day value
const std::string DayOfWeek::days[7] = {"sun", "mon", "tue", "wed", "thu", "fri", "sat"};
DayOfWeek::DayOfWeek() {
}
DayOfWeek::DayOfWeek(int dayNum)
{
day = dayNum;
}
DayOfWeek::DayOfWeek(std::string dayWord)
{
day = 0; // set Sunday as default
// truncate the string to 3 letters
if (dayWord.length() > 3)
dayWord = dayWord.substr(0, 3);
// to lower case - makes comparison case insensitive
std::transform(dayWord.begin(), dayWord.end(), dayWord.begin(), [](unsigned char c) { return std::tolower(c);});
// compare with our list of strings, if none found, it will stay as default
for (int i = 0; i < 7; ++i)
if (days[i] == dayWord)
{
day = i;
break;
}
}
void DayOfWeek::outputDayLetters() {
std::cout << std::endl << "Day Letters: " << days[day];
}
void DayOfWeek::outputDayNumber() {
std::cout << std::endl << "Day Numbers: " << day;
}
int main()
{
int dayNum;
std::string dayWord;
std::cout << std::endl << "Enter a weekday: ";
std::cin >> dayWord;
std::cout << std::endl << "You entered " << dayWord;
DayOfWeek dayObject = DayOfWeek(dayWord);
dayObject.outputDayNumber();
dayObject.outputDayLetters();
}
#include <h1>iostream <h2>
#include <h1>cmath<h2>// for + of months, days, and years
#include <h1>fstream<h2> //for in and output
#include <h1>cstdlib<h2>
#include <h1>string<h2>//for string type
using namespace std;
class Device {//Input and store Device Description and Serial Numbers
protected:
string serial_number;
string device_description;
public:
Device() {
serial_number = ("6DCMQ32");
device_description = ("TheDell");
}
Device(string s, string d) {
serial_number = s;
device_description = d;
}
};
class Test {
protected:
string Test_Description;
static int recent_month, recent_day, recent_year, new_month;
static int nmonth, next_month, next_day, next_year, max_day;
public:
static void getMonth() {//Calculates the next/new month
next_month = recent_month + nmonth;
new_month = next_month % 12;
if (next_month >= 12) {
cout << "The next Date: " << new_month << " / ";
}
else {
cout << "The next Date: " << next_month << " / ";
}
}
static void getDay() { //Calculates day of next month
if (new_month == 4 || new_month == 6 || new_month == 9 || new_month == 11) {
max_day = 30;
}
else if (new_month == 2) {
max_day = 29;
}
else {
max_day = 31;
}
if (recent_day > max_day) {
cout << max_day << " / ";
}
else {
cout << recent_day << " / ";
}
}
static void getYear() {//Calculates the year of the next number of months
next_year = recent_year + next_month;
if (next_year >= 12) {
cout << recent_year + (next_month / 12) << endl;
}
else {
cout << next_year << endl;
}
}
static void getDate() {
Test::getMonth(), Test::getDay(), Test::getYear();
}
};
int Test::recent_month, Test::recent_day, Test::recent_year,
Test::new_month;
int Test::nmonth, Test::next_month, Test::next_day, Test::next_year,
Test::max_day;
class Lab : public Device, public Test {//Class Lab is a Child of Class Test and Class Device
protected:
static int n;
public:
friend istream & operator>>(istream & cin, const Lab & lab) {
cout << "Enter Device Description and serial number: ";
getline(cin, lab.device_description);//This is where the error is
getline(cin, lab.serial_number);//This is where the error is
cout << "Enter Test Description: ";
getline(cin, lab.Test_Description);//This is where the error is
cout << "Enter number of months: ";
cin >> lab.nmonth;
cout << "Enter the most recent date(mm/dd/yyyy): ";
cin >> lab.recent_month >> lab.recent_day >> lab.recent_year;
return cin;
}
friend ostream & operator<<(ostream & cout, const Lab & lab) {
cout << lab.device_description << " ";
cout << lab.serial_number << endl;
cout << lab.Test_Description << endl;
getDate();
return cout;
}
static void getFile() {
cout << "Enter the number of devices: ";
cin >> n;
Lab *obj = new Lab[n];
if (obj == 0) {
cout << "Memory Error";
exit(1);
}
for (int i = 0; i<n; i++) {
cin >> obj[i];
}
ofstream myfile("Device.dat", ios::binary);
myfile.write((char *)obj, n * sizeof(Lab));
Lab *obj2 = new Lab[n];
ifstream file2("Device.dat", ios::binary);
if (obj2 == 0) {
cout << "Memory Error";
exit(1);
}
file2.read((char *)obj2, n * sizeof(Lab));
for (int i = 0; i < n; i++) {
cout << obj2[i];
cout << endl;
}
delete[] obj2;
}
void getSearch(){
}
};
void main() {
Lab L;
L.getFile();
system("pause");
}
//Error C2665 'std::getline': none of the 2 overloads could convert all
the argument types
/*
Purpose: is to enter the number of months for the next test date of device with input of serial number, Device Description, Test Description, recent date, and the number of months of two tests. At the end the program must be searched by having the user to input the serial number and the next date, if these two are valid everything in the device is listed out.
*/<
You shouldn't name your parameters like objects of the standard library (cin).
For an argument to be modifiable it must not be a reference to a constant entity.
Also, a std::istream bound operator<<() overload should not do output, but only extract the object required from the stream.
In my main I have to test the class i made with a for loop but am a little stuck. I have to loop through 3 times and get user input for the ticketing system. I tried making an array and storing the user input but nothing I have tried so far has worked. Im trying to call upon the SetWorkTicket with my loop.
#include<iostream>
#include<iomanip>
#include<stdexcept>
#include<sstream>
using namespace std;
// start of the WorkTicket class
class WorkTicket{
public:
// defailt constructors, if the parameters are not specified the ticket will be set to 0 and the date to 1/1/2000. The rest empty strings
WorkTicket() : myTicketNumber(0), myClientId(""), myDay (1), myMonth (1), myYear(2000), myDescription ("") { }
WorkTicket(int ticketNumber, string clientId, int month, int day, int year, string description);
// mutator method that sets all attributes of the object to the parameters as long as valid. If no problems are being detected set TRUE if not then FALSE.....
bool SetWorkTicket(int ticketNumber, string clientId, int month, int day, int year, string description);
// accessor method that will show all the attributes of the ticket in the console menu
void ShowWorkTicket() const;
// here are the sets and gets for the attributes
// ticket number
void SetTicketNumber(int ticketNumber);
int GetTicketNumber() const {return myTicketNumber;}
// client id
void SetClientId(string clientId) {myClientId = clientId;}
string GetClientId() const { return myClientId;}
// date by day
void SetDay(int day);
int GetDay() const { return myDay; }
// date by month
void SetMonth(int month);
int GetMonth() const { return myMonth; }
// date by year
void SetYear(int year);
int GetYear() const { return myYear; }
// description
void SetDescription(string description) { myDescription = description; }
string GetDescription() const { return myDescription; }
private:
int myTicketNumber;
string myClientId;
int myDay;
int myMonth;
int myYear;
string myDescription;
};
// the work ticket constructor definition
WorkTicket::WorkTicket(int ticketNumber, string clientId, int month, int day, int year, string description)
{
SetTicketNumber(ticketNumber);
SetClientId(clientId);
SetMonth(month);
SetDay(day);
SetYear(year);
SetDescription(description);
}
// set work ticket
bool WorkTicket::SetWorkTicket(int ticketNumber, string clientId, int month, int day, int year, string description)
{
const int MAX_DAY = 31; // setting max day to 31
const int MAX_MONTH = 12; // max month to 12
const int MIN_YEAR = 2000; // the min year 2000 as specified
const int MAX_YEAR = 2099; // max year 2099 as speciified
bool valid = true;
// setting the limits
if(ticketNumber < 0 || month < 1 || month > MAX_MONTH ||
day < 1 || day > MAX_DAY ||
year < MIN_YEAR || year > MAX_YEAR)
valid = false;
else if (clientId.length() < 1 || description.length() < 1)
valid = false;
else
{
myTicketNumber = ticketNumber;
myClientId = clientId;
myDay = day;
myMonth = month;
myYear = year;
myDescription = description;
}
return valid;
}
// this is to show the work ticket, it will show everything in the console..
void WorkTicket::ShowWorkTicket() const
{
cout << "\nWork Ticket Number: " << myTicketNumber
<< "\nClient ID: " << myClientId
<< "\nDate: " << setw(2) << setfill('0') << myMonth
<< "/" << setw(2) << setfill('0') << myDay
<< "/" << myYear
<< "\nIssue: " << myDescription << endl;
}
void WorkTicket::SetTicketNumber(int ticketNumber)
{
if(ticketNumber > 0)
{
myTicketNumber = ticketNumber;
}
else
{
throw invalid_argument("Try Again.");
}
}
// WorkTicket::SetDay definition
void WorkTicket::SetDay(int day)
{
const int MIN_VALID = 1;
const int MAX_VALID = 31;
if(day >= MIN_VALID && day <= MAX_VALID)
{
myDay = day;
}
else
{
throw invalid_argument("Try Again.");
}
}
// WorkTicket::SetMonth definition
void WorkTicket::SetMonth(int month)
{
const int MIN_VALID = 1;
const int MAX_VALID = 12;
if(month >= MIN_VALID && month <= MAX_VALID)
{
myMonth = month;
}
else
{
throw invalid_argument("Try Again.");
}
}
// WorkTicket::SetYear definition
void WorkTicket::SetYear(int year)
{
const int MIN_VALID = 2000;
const int MAX_VALID = 2099;
if(year >= MIN_VALID && year <= MAX_VALID)
{
myYear = year;
}
else
{
throw invalid_argument("Try Again.");
}
}
int main()
{
const int NUMBER_OF_TICKETS = 3;
WorkTicket tickets[NUMBER_OF_TICKETS];
int ticketNumber;
string clientId;
int day;
int month;
int year;
string description;
for (int i = 0; i <NUMBER_OF_TICKETS; i++)
{
cout << "\WorkTicket [" << i << "]: " << endl;
cout << "Enter the ticket number: " << endl;
cout << "Enter the client ID: " << endl;
getline(cin, clientId);
day = SetDay("Enter a day number: ");
}
}
Gather the input and then construct a WorkTicket. Push the tickets into a vector. In the code yet to be written, the newly create WorkTickets can be tested for correctness.
Make sure to include vector at the top of the file.
int main()
{
const int NUMBER_OF_TICKETS = 3;
int ticketNumber;
string clientId;
int day;
int month;
int year;
string description;
std::vector<WorkTicket> tickets;
for (int i = 0; i <NUMBER_OF_TICKETS; i++)
{
cout << "WorkTicket [" << i << "]: " << endl;
cout << "Enter the ticket number: " << endl;
cin>> ticketNumber;
cout << "Enter the client ID: " << endl;
cin >> clientId;
cout << "Enter a day number: " << endl;
cin >> day;
cout << "Enter a month number: " << endl;
cin>> month;
cout << "Enter a year number: " << endl;
cin>> year;
cout << "Enter a description : " << endl;
cin >> description;
try {
tickets.push_back({ticketNumber, clientId, month, day, year, description});
}
catch(std::exception e)
{
std::cout << e.what() << std::endl;
}
}
}
Assuming the rest of your code works correctly and you only have problems in the main:
There are a few issues as commented by others in your code in main:
1) You declared WorkTicket tickets[NUMBER_OF_TICKETS]; but have not used it anywhere.
2) The variable tickets is an array and therefore in the for loop tickets[i] is of type WorkTicket.
3) SetDay is a member function of WorkTicket and takes int as argument.
In light of these, following changes made:
for (int i = 0; i <NUMBER_OF_TICKETS; i++)
{
cout << "\WorkTicket [" << i << "]: " << endl;
cout << "Enter the ticket number: " << endl;
cout << "Enter the client ID: " << endl;
getline(cin, clientId);
cout<<"Enter a day number:";
int day;
cin>>day;
tickets[i].SetDay(day); //day is int and tickets[i] is of WorkTicket
}
Hope this helps to understand the main part better.
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 6 years ago.
Improve this question
I am having a fairly frustrating issue where I attempt to pass the contents of a pointer array that is filled with objects to another class so that I may print the contents of the Array but no matter what I have tried to do in changing the way I pass the array I consistently get a Segmentation Fault. I have looked all around for people with similar problems and I did not manage find anyone with the same issue but still I apologize if this is a duplicate question!
anyways, my code for these two classes is
#include <iostream>
#include <vector>
#include <string>
using namespace std;
//Time Class
class Time{
public:
Time();
void setHour(int sHour){hour = sHour;}
void setMinute(int sMinute){minute = sMinute;}
void setAmPm(int sAmPm){ampm = sAmPm;}
int getHour(){return hour;}
int getMinute(){return minute;}
int getAmPm(){return ampm;}
private:
int hour;
int minute;
int ampm;
};
//Time Constructor implementation
Time::Time(){
hour = 0;
minute = 0;
ampm = 0;
}
//Event Class
class Event{
public:
Event(string x, Time y);
void setDesc(string sDesc){description = sDesc;}
string getDesc(){return description;}
void setTime(Time t, int h, int m, int ampm){t.setHour(h); t.setMinute(m); t.setAmPm(ampm);}
Time getTime(){return eventTime;}
printEvent(Event e){
Time t = e.getTime();
cout << description << endl;
string ampm ="";
if(t.getAmPm() == 0)
ampm = "AM";
else
ampm = "PM";
cout << t.getHour() << ":" << t.getMinute() << " in the " << ampm;
}
private:
string description;
Time eventTime;
};
//Event Constructor implementation
Event::Event(string cDesc, Time t){
description = cDesc;
eventTime = t;
}
//Month Class
class Month{
public:
Month(string x, int y);
void addEvent(string desc, int h, int m, int ampm, int day){
Time t;
t.setHour(h);
t.setMinute(m);
t.setAmPm(ampm);
Event e(desc, t);
this -> event[day] = &e;
}
void deleteEvent(int day){delete event[day];}
Event getEvent(int day){
return *event[day];
}
void displayEvent(int day){
Event e = getEvent(day);
e.printEvent(e);
}
void displayAll(int days){
// Time t;
// Event e("StupidSolution", t);
// for(int i = 0; i < days; i++)
// e.printEvent(*event[i]);
}
private:
int days;
string month;
Event* event[31];
};
//Month Constructor implementation
Month::Month(string cMonth, int cDays){
days = cDays;
month = cMonth;
}
//both num days and find month are used to determine the Month the user wants to generate a calendar for and the amount of days in that month
string findMonth(int numMonth){
if(numMonth == 1)
return "January";
if(numMonth == 2)
return "February";
if(numMonth == 3)
return "March";
if(numMonth == 4)
return "April";
if(numMonth == 5)
return "May";
if(numMonth == 6)
return "June";
if(numMonth == 7)
return "July";
if(numMonth == 8)
return "August";
if(numMonth == 9)
return "September";
if(numMonth == 10)
return "October";
if(numMonth == 11)
return "November";
if(numMonth == 12)
return "December";
}
int numDays(int numMonth){
if(numMonth == 1)
return 31;
if(numMonth == 2)
return 28;
if(numMonth == 3)
return 31;
if(numMonth == 4)
return 30;
if(numMonth == 5)
return 31;
if(numMonth == 6)
return 30;
if(numMonth == 7)
return 31;
if(numMonth == 8)
return 31;
if(numMonth == 9)
return 30;
if(numMonth == 10)
return 31;
if(numMonth == 11)
return 30;
if(numMonth == 12)
return 31;
}
//gets all necessary info from user for creating a new event
void newEvent(int day, Month month){
string desc = "";
int h = 0;
int m = 0;
int ampm = 0;
cin.get();
cout << "Please enter a Brief Description of the Event!: " << endl;
getline(cin, desc);
cout << "Please enter the Hour of event(1-12): " << endl;
cin >> h;
cout << "Please enter the Minute of event (0-59): " << endl;
cin >> m;
cout << "Please enter 0 if it is in the AM and 1 if it is in the PM: " << endl;
cin >> ampm;
month.addEvent(desc, h, m, ampm, day);
}
int main(void){
string month = "";
int numMonth = 0;
int menuChoice = 0;
int menuLoop = 0;
int days = 0;
int eDay = 0;
cout << "please enter the month you would like to track(1-12): ";
cin >> numMonth;
days = numDays(numMonth);
month = findMonth(numMonth);
Month m(month,days);
while(menuLoop == 0){
cout << "Event Calendar for the month of " << month << endl;
cout << "1. Create a new Event" << endl;
cout << "2. Delete an existing Event" << endl;
cout << "3. Display Event for a particular day" << endl;
cout << "4. Display All Events" << endl;
cout << "5. Exit Program" << endl;
cout << "Enter Choice: " << endl;
cin >> menuChoice;
switch(menuChoice){
case 1:
cout << "What day would you like this event to be on?" << endl;
cin >> eDay;
if(eDay > 0 && eDay <= days)
newEvent(eDay, m);
else cout << "Invalid Day";
break;
case 2:
cout << "What day would you like to clear of events?" << endl;
cin >> eDay;
if(eDay > 0 && eDay <= days)
m.deleteEvent(eDay);
break;
case 3:
cout << "What day would you like to View?" << endl;
cin >> eDay;
if(eDay > 0 && eDay <= days)
m.displayEvent(eDay);
break;
case 4:
cout << "Displaying all Events.";
m.displayAll(days);
break;
case 5:
cout << "Goodbye!" << endl;
menuLoop++;
break;
default:
cout << "incorrect input";
break;
}
}
}
The important bits are the Event* event[31]; array, the displayEvent and the PrintEvent functions. I have tried all forms of passing by reference and de-referencing the array as I pass it but nothing seems to fix the issue...
Thank you so much!
Edit: added the remainder of the program, the segmentation fault occurred after creating a new event (option 1 on the menu) then either trying to delete it (option 2) or display it (option 3)
This function:
void addEvent(string desc, int h, int m, int ampm, int day){
Time t;
t.setHour(h);
t.setMinute(m);
t.setAmPm(ampm);
Event e(desc, t);
this -> event[day] = &e;
}
Creates a new Event e on the stack. Then it saves a pointer to that local variable. As soon as your function returns, that pointer is no longer valid and using it will result in undefined behavior (such as a seg fault, but it could do many other things).
To fix it, work out whether those arrays should be arrays of pointers, or just arrays of objects. If you definitely want to use pointers, then you will need to work out how you control their life time. Alternatively, you could use a smart pointer that will look after the object's lifetime for you.
Note: this is just the first thing that jumped out at me, there may be other problems.
I am having trouble displaying "next day" in the correctly in my program. The assignment states, ".The user is prompted to enter the hour, min, second of the current processing time - currTime. Your program will compute the next processing time which is 30 mins after the current processing time. Your program will display the current processing timetime currTime and the next processing time 1 nextTime1 following processing time 2 nextTime2. If the next processing time goes to the next day then
you display “Next Day” next to the next processing time (see sample output).
The sample output shows:
Current Proc Time = 23:50:10 | Next Proc Time = 0:20:10 (Next Day) | Next Proc Time 2 = 0:50:10
My problem occurs during the bold line "Next Proc Time 2 = 0:50:10," in my code it displays (Next Day) in which it should not, only for the previous line, "Next Proc Time (Next Day" should it be displayed. So my question is what should I do to alter my code under the Void TimeType::Display() function to have it display "Next Day" when the day is equal to one correctly. Also, I apologize if my question is not too specific, I am just at a loss and do not know what to do to fix this issue.
#ifndef TIME_H
#define TIME_H
class TimeType { //class definition
private:
int sec;
int min;
int hr;
int day; // variable stores the information about the day, you need to track the transition to the next day
public:
TimeType();
void SetTime(int s, int m, int h, int d);
TimeType NextProcTime(void);
void Display();
};
#endif
#include <iostream>
#include <stdlib.h>
#include <stdio.h>
#include "timetype.h"
using namespace std;
TimeType::TimeType()
{
sec = 0;
min = 0;
hr = 0;
}
void TimeType::SetTime(int s, int m, int h, int d)
{
sec = s;
min = m;
hr = h;
day = d;
}
TimeType TimeType::NextProcTime(void)
{
long buf = 0;
int h, m, s, d;
buf = (day * 86400 + hr * 3600 + min * 60 + sec) + (30 * 60); //calculation time in seconds needed for the allocation of time to reflect additional minutes
d = buf / 86400; // recalculation time for days hours minutes seconds
h = (buf - 86400 * d) / 3600;
m = (buf - 86400 * d - 3600 * h) / 60;
s = (buf - 86400 * d - 3600 * h - 60 * m);
TimeType T; //creating a buffer TimeType object
T.SetTime(s, m, h, d); //full a buffer TimeType object
return T; //return buffer TimeType object
}
void TimeType::Display()
{
if (day == 1)
{
printf(" %02i:%02i:%02i (next day)\t", hr, min, sec);
}
else {
printf(" %02i:%02i:%02i \t", hr, min, sec);
}
};
int main(int argc, char *argv[])
{
int hr = 0, min = 0, sec = 0;
TimeType currTime, nextTime1, nextTime2;
char t;
do
{
system("cls");
while (1) {
cout << "Please enter the current processing hour." << endl;
cin >> hr;
if (hr >= 0 && hr < 24)
break;
cout << "Invalid Input, try again." << endl << endl;
}
cout << endl;
while (1)
{
cout << "Please enter the current processing minute." << endl;
cin >> min;
if (min >= 0 && min < 60)
break;
cout << "Invalid Input, try again." << endl << endl;
}
cout << endl;
while (1)
{
cout << "Please enter the current processing second." << endl;
cin >> sec;
if (sec >= 0 && sec < 60)
break;
cout << "Invalid Input, try again." << endl << endl;
}
cout << endl;
currTime.SetTime(sec, min, hr, 0);
nextTime1 = currTime.NextProcTime();
nextTime2 = nextTime1.NextProcTime();
cout << "Current Proc Time = ";
currTime.Display();
cout << endl;
cout << "Next Proc Time 1 = ";
nextTime1.Display();
cout << endl;
cout << "Next Proc Time 2 = ";
nextTime2.Display();
cout << endl;
cout << endl << "Do you have more data to enter? (y/n)" << endl;
cin >> t;
cout << endl;
} while (t == 'y'); // cycle for program multiple using
return 0;
}