Hopefully someone can help because I'm lost. When running my program earlier, it worked fine, now for some reason I get the error message
fatal error C1010: unexpected end of file while looking for precompiled header. Did you forget to add '#include "stdafx.h"' to your source?
which I did include the header. The goal was to create a program which prints the time and date and be able to input the size of the window and font and background color having two different files. The first file is as follows.
#include "TimeClass.h"
////////////////////////////////////////////////////////////////////////////
// Class to help with the usage of time.
//////////////////////////////////////////////////////////////////////////
CTimeClass::CTimeClass()
{
// Notice that the time is stored whenever this time object is created.
// Use this to your advantage in "main".
// "m_st" holds the time and date information.
GetLocalTime(&m_st);
}
////////////////////////////////////////////////////////////////////////
CTimeClass::~CTimeClass()
{
// Empty - Nothing to destroy here.
}
short CTimeClass::Year()
{
// Place your code here to return the year as a short.
ConsoleTime ct;
short year = ct.wYear;
return year;
}
///////////////////////////////////////////////////////////////////////////
string CTimeClass::Month()
{
ConsoleTime ct;
int month = cm.wMonth;
if (month == 0)
return "January";
else if (month == 1)
return "February";
else if (month == 2)
return "March";
else if (month == 3)
return "April";
else if (month == 4)
return "May";
else if (month == 5)
return "June";
else if (month == 6)
return "July";
else if (month == 7)
return "August";
else if (month == 8)
return "September";
else if (month == 9)
return "October";
else if (month == 10)
return "November";
else if (month == 11)
return "December";
else
return "error";
// Place your code here to return the month as a string.
}
//////////////////////////////////////////////////////////////
short CTimeClass::Day()
{
ConsoleTime ct;
short day = ct.wDay;
return day;
// Place your code here to return the day as a short.
}
//////////////////////////////////////////////////////////////////////
string CTimeClass::DayOfWeek()
{
ConsoleTime ct;
int day == st.wDayOfWeek;
if (day == 0)
return "Sunday";
else if (day == 1)
return "Monday";
else if (day == 2)
return "Tuesday";
else if (day == 3)
return "Wednesday";
else if (day == 4)
return "Thursday";
else if (day == 5)
return "Friday";
else if (day == 6)
return "Saturday";
else
return "error";
// Place your code here to return the day of the week as a string.
}
//////////////////////////////////////////////////////////////////
short CTimeClass::Hour()
{
ConsoleTime ct;
short hour = ct.wHour;
return hour;
// Place your code here to return the hour as a short.
}
///////////////////////////////////////////////////////////////////////////
short CTimeClass::Minute()
{
ConsoleTime ct;
short minute = ct.wMinute;
return minute;
// Place your code here to return the minute as a short.
}
///////////////////////////////////////////////////////////////////////////
short CTimeClass::Second()
{
ConsoleTime ct;
short second = ct.wSecond;
return second;
// Place your code here to return the second as a short.
}
Below is my second file.
// ConsoleWindowClock.cpp : Defines the entry point for the console
application.
//
#include "stdafx.h"
#include "ConsoleClass.h"
#include "TimeClass.h"
#include <iomanip>
#include <iostream>
#include <windows.h>
#include <stdlib.h>
using namespace std;
int main()
{
int width;
int height;
int fontsize;
int text;
int background;
int userclass;
int time;
userclass.ConsoleColor(text, background);
userclass.ConsoleWindowSize(width, height);
userclass.FontSize(fontsize);
cout << "This is the console window clock" << endl;
cout << "Please enter the window size in characters: " << endl;
cin >> width;
cin >> height;
cout << "Please enter the font size: " << endl;
cin >> fontsize;
cout << "Enter the Text color (0=Red, 1=Green, 2=Blue, -1=Random): " <<
endl;
cin >> text;
cout << "Enter the background color (0=Red, 1=Green, 2=Blue, -1=Random): "
<< endl;
cin >> background;
while (true)
{
cout << "The time is: " << time.Hour() << ":" << time.Minute() << ":" <<
time.Second() << endl;
cout << "The day of the week is: " << time.DayOfWeek() << endl;
cout << "The month, day, and year are: " << time.Month() << " " <<
time.Day() << ", " << time.Year() << endl;
Sleep(1000);
}
return 0;
}
Any help would be greatly appreciated, sorry for the long post.
You have messed up comments:
// ConsoleWindowClock.cpp : Defines the entry point for the console
application.
//
should be
// ConsoleWindowClock.cpp : Defines the entry point for the console
// application.
Also you should include precompiled header before TimeClass.h in the first file.
#include "stdafx.h"
#include "TimeClass.h"
Have you reviewed your "TimeClass.h"? I had seen similar error which was originated from the .h file.
I know this should be in a comment but don't have enough repute for that :(
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();
}
I found an RPS game and wanted to improve on it by creating a scoring system but the //int compwin = compwin + 1; keeps giving me errors. I am still fairly new to coding in C++ and have no clue where the problem is standing so thanks for helping in advance. Also this code was taken from somewhere this is not my code but I wanted to try and improve on it.
#include <iostream>
#include <cstdlib>
#include <limits>
#include <ctime>
#include <string>
using namespace std;
int main()
{
int choice;
int i;
int y;
int Y;
int comp;
char res;
int compwin = 0;
int choicewin = 0;
unsigned seed;
while (1==1) {
//The choices
cout << "Game Choices.\n\n";
cout << "1.Rock\n";
cout << "2.Paper\n";
cout << "3.Scissors\n";
cout << "4.Quit, exits the game.\n\n";
cout << "Please enter your choice.\n\n";
cin >> choice;
//-----------------------Player Imputs-----------------------------------
if (choice == 1) //Rock
{
cout << "You picked Rock.\n";
cout << "Now here was my choice.\n\n";
}
else if (choice == 2) //Paper
{
cout << "You picked Paper.\n";
cout << "Now here was my choice.\n\n";
}
else if (choice == 3) //Scissors
{
cout << "You picked Scissors.\n";
cout << "Now here was my choice.\n\n";
}
else if (choice == 4)
{
return 0;
}
else if (choice != 1 || 2 || 3 || 4) // Debug
{
cout << "Uhhhh thats not one of the following.\n\nGoodbye!\n\n";
system("pause");
return 0;
}
//-------------------------Computer Choice-------------------------------
seed = time(0);
srand(seed); //RNG TIME
comp = rand() % 3 + 1; //Computer picks
if (comp == 1) //Computer rock
{
res = 1;
cout << "Rock!\n\n";
}
else if (comp == 2) //Computer paper
{
res = 2;
cout << "Paper!\n\n";
}
else if (comp == 3) // Computer scissors
{
res = 3;
cout << "Scissors!\n\n";
}
//-----------------------Victory Conditions------------------------------
if (comp == 1 && choice == 1) {
std::cout << "It was a tie!" << endl;
}
else if (comp == 1 && choice == 3) {
std::cout << "I Won! Better luck next time!" << endl;
//int compwin = compwin + 1; This is where the problem occurs
}
else if (comp == 2 && choice == 2) {
std::cout << "It was a tie!" << endl;
}
else if (comp == 2 && choice == 1) {
std::cout << "I Won! Better luck next time!" << endl;
//int compwin = compwin + 1; This is where the problem occurs
}
else if (comp == 2 && choice == 3) {
std::cout << "It was a tie!" << endl;
}
else if (comp == 2 && choice == 2) {
std::cout << "I Won! Better luck next time!" << endl;
//int compwin = compwin + 1; This is where the problem occurs
}
else {
std::cout << "Congrats! You won!" << endl;
//int choicewin = choicewin + 1; This is where the problem occurs
}
cout << "Heres the score, computer =" << compwin << "and player =" << choicewin;
cout << "Want to go again? (y/n)";
cin >> res;
system("cls");
}
while (res == y || Y);
system("pause");
return 0;
}
This
int compwin = compwin + 1;
is a declaration and initialization. A rather weird one, and to discuss why it is allowed would take us on a too big detour. So lets look at a simpler example:
int compwin = 1; // declares compwin and initializes it with 1
int compwin = 2; // compiler error, because compwin is already declared
You can only declare the same variable once (again the long complete truth is more involved, search for "shadowing" in case you care). You also only need to initialize a variable only once.
If you want to assign something to an already declared variable, you use assignment, as in
int compwin = 1; // declare and initialize
compwin = 2; // assign
Further note that
else if (choice != 1 || 2 || 3 || 4) // Debug
is not doing what you expect. The correct way is
else if (choice != 1 && choice != 2 && choice != 3 && choice != 4)
The mistake is a combination of ignoring De Morgan's Law and a wrong combination of several conditions. The operator|| expects a bool on both sides and unfortunately numbers happily convert to true (only 0 becomes false), but a good compiler may spit out warnings on that. Similar mistake is on while (res == y || Y);.
I am Tony and I am new to c++ programming. I would like to ask a question related to creating a program to check for leap year.
In the following codes, I try to create a bool function to check whether the input is a leap year. If the input is negative, I will cout "Bye!" and stop the program immediately. If the input is positive, then I will check whether it is a leap year using the bool function I built until the input is a negative number then I will exit the program.
However, I am not able to find what mistakes I have made and the current situation is, when I input a positive value, there is no result generated. Please help if you are available. Much thanks to you. : )
#include <iostream>
#include <cmath>
#include <string>
#include <iomanip>
using namespace std;
bool leap_year(int year);
int main()
{
int year;
while (cout << "Enter a year (or negative number to quit): ")
{
cin >> year;
if (leap_year(year) == false && year <0 )
{
cout << "Bye!" << endl;
}
break;
if (leap_year(year) == false && year >0 )
{
cout << "The year is not a leap year." << endl;
}
if (leap_year(year) == true && year >0 )
{
cout << "The year is a leap year." << endl;
}
return 0;
}
}
bool leap_year(int year)
{
bool is_leap_year = false;
if (year % 4 == 0)
{
is_leap_year = true;
}
if (year % 100 == 0)
{
is_leap_year = false;
}
if (year % 400 == 0)
{
is_leap_year = true;
}
return is_leap_year;
}
First of all, you (should) want a while(true) loop and not a while(std::ostream) loop.
So replace
while (cout << "Enter a year (or negative number to quit): ")
{
with
while (true)
{
cout << "Enter a year (or negative number to quit): ";
As #paddy pointed out, you can check std::ostream`s return type to look for errors when printing out. But in this simple program I doubt it's necessary.
Then you have the break outside your if statement, which will always break out of the program (no matter the Input). Replace
if (leap_year(year) == false && year <0 )
{
cout << "Bye!" << endl;
}
break;
with
if (year < 0)
{
cout << "Bye!" << endl;
break;
}
(there's no need to check if the negative input is a leap year. You can achieve entering only 1 if-statement with if-else statments, therefore you can also replace if(leap_year(year) == false && year < 0) with just if (year < 0); as I did.)
When you apply this to all statements (not changing their internal logic) and remove the return 0; at the end of the loop, you get your desired program flow. Also removing using namespace std; is just better (read here why). You also don't Need to include <iomanip>, <cmath> nor <string>. Full Code:
#include <iostream>
bool leap_year(int year);
int main() {
int year;
while (true) {
std::cout << "Enter a year (or negative number to quit): ";
std::cin >> year;
if (year < 0) {
std::cout << "Bye!" << std::endl;
break;
}
else if (leap_year(year)) {
std::cout << "The year is a leap year." << std::endl;
}
else {
std::cout << "The year is not a leap year." << std::endl;
}
}
}
bool leap_year(int year){
bool is_leap_year = false;
if (year % 4 == 0){
is_leap_year = true;
}
if (year % 100 == 0){
is_leap_year = false;
}
if (year % 400 == 0){
is_leap_year = true;
}
return is_leap_year;
}
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.
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 8 years ago.
Improve this question
I am having to write a program for a class I'm taking. I have to take a birth date in numerical form (mm-dd-yyyy) and put it into a different format (Month day, year). I feel like my code is correct, but whenever my do while loop gets to the hyphen, it crashes. It compiles correctly, and Visual Studio isn't popping up any error until it runs, so I really don't know what's wrong. I've included the entire code. Also, use of the try/catch block is required for this assignment. Can anyone tell me why this loop doesn't like to check for hyphens? Thanks in advance.
#include <iostream>
#include <string>
using namespace std;
int get_digit(char c) {return c - '0';}
int main() {
string entry = "";
short month = 0;
int day = 0;
int year = 0;
bool error = false;
int temp = 0;
try {
cout << "Enter your birthdate in the form M-D-YYYY: ";
cin >> entry;
int x = 0;
do {
month *= 10;
temp = get_digit(entry[x]);
month += temp;
x += 1;
} while (entry[x] != '-');
if (month > 12) {
throw month;
}
x += 1;
do {
day *= 10;
temp = get_digit(entry[x]);
day += temp;
x += 1;
} while (entry[x] != '-');
if (month == 1 || month == 3 || month == 5 || month == 7 || month == 8 || month == 10 || month == 12) {
if (day > 31) {
throw day;
}
} else if (month == 4 || month == 6 || month == 9 || month == 11) {
if (day > 30) {
throw day;
}
} else {
if (day > 29) {
throw day;
}
}
x += 1;
do {
year *= 10;
temp = get_digit(entry[x]);
year += temp;
x += 1;
} while (entry[x] != '\n');
if ((year % 4) != 0) {
if (month == 2 && day > 28) {
throw day;
}
}
switch (month) {
case 1:
cout << "January ";
case 2:
cout << "February ";
case 3:
cout << "March ";
case 4:
cout << "April ";
case 5:
cout << "May ";
case 6:
cout << "June ";
case 7:
cout << "July ";
case 8:
cout << "August ";
case 9:
cout << "September ";
case 10:
cout << "October ";
case 11:
cout << "November ";
case 12:
cout << "December ";
}
cout << day << ", " << year << endl;
} catch (short) {
cout << "Invalid Month!" << endl;
} catch (int) {
cout << "Invalid Day!" << endl;
}
system("pause");
return 0;
}
There is no newline character in your entry string, so x keeps getting incremented and causes buffer overrun for entry[x]. You need to look for the end of the string instead:
do {
year *= 10;
temp = get_digit(entry[x]);
year += temp;
x += 1;
} while (entry[x] != '\0');