How can I search for a character in a string? - c++

I'm writing a program that converts a short date (mm/dd/yyyy) to a long date (March 12, 2014) and prints out the date.
The program has to work given the following user inputs:
10/23/2014
9/25/2014
12/8/2015
1/1/2016
I have the program working with the first user input but I'm not sure how to proceed with handling a user input that doesn't have a "0" in the first position of the string.
#include <iostream>
#include <string>
using namespace std;
int main()
{
string date;
cout << "Enter a date (mm/dd/yyyy): " << endl;
getline(cin, date);
string month, day, year;
// Extract month, day, and year from date
month = date.substr(0, 2);
day = date.substr(3, 2);
year = date.substr(6, 4);
// Check what month it is
if (month == "01") {
month = "January";
}
else if (month == "02") {
month = "February";
}
else if (month == "03") {
month = "March";
}
else if (month == "04") {
month = "April";
}
else if (month == "05") {
month = "May";
}
else if (month == "06") {
month = "June";
}
else if (month == "07") {
month = "July";
}
else if (month == "08") {
month = "August";
}
else if (month == "09") {
month = "September";
}
else if (month == "10") {
month = "October";
}
else if (month == "11") {
month = "November";
}
else {
month = "December";
}
// Print the date
cout << month << " " << day << "," << year << endl;
return 0;
}
I'd greatly appreciate any help.

As Red Serpent wrote in the comments: Search for the / using std::string::find, e.g.
#include <iostream>
int main()
{
std::string date = "09/28/1983";
int startIndex = 0;
int endIndex = date.find('/');
std::string month = date.substr(startIndex, endIndex);
startIndex = endIndex + 1;
endIndex = date.find('/', endIndex + 1);
std::string day = date.substr(startIndex, endIndex - startIndex);
std::string year = date.substr(endIndex + 1, 4);
std::cout << month.c_str() << " " << day.c_str() << "," << year.c_str() << std::endl;
return 0;
}

You could also take advantage of stream conversion, for a less efficient but simpler solution:
#include <iostream>
#include <string>
using namespace std;
int main() {
string months[] = {"", "January", "February", "Mars", "April", "May", "June", "Jully", "August", "September", "October", "December"};
cout << "Enter a date (mm/dd/yyyy): " << endl;
char c;
int day, month, year;
cin >> day >> c >> month >> c >> year;
// error handling is left as an exercice to the reader.
cout << months[month] << " " << day << ", " << year << endl;
return 0;
}

Related

Using Classes for Day of the Week

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();
}

How can we transform a string in integer without stoi command / to input date and output integers

#include <iostream>
using namespace std;
int daysMonth (int month) // the part to clarify
{
if (month >= 1 && month <= 12){
if (month == 2)
return 28;
if (month == 4 || month == 6 || month == 9 || month == 11)
return 30;
return 31;
}
return 0;
}
void nextDay (int day, int month, int year) // nextday conditions
{
int daysOfMonth = daysMonth(month);
if ((year % 4 == 0) && (year % 100 != 0) || year % 400 == 0)
{
if (day == 28){
day = 29;
month = month;
year = year;
}
}
if (day != daysOfMonth)
{
day = day + 1;
month = month;
year = year;
}
if (day == daysOfMonth)
{
day = 1;
month = month + 1;
year = year;
}
if ((month == 12) && (day == 31))
{
day = 1;
month = 1;
year = year + 1;
}
cout << "Next day is : " << day << "/" << month << "/" << year << endl;
}
int main(){
int day;
int month;
int year;
cout << "Enter a date : " << endl;
cin >> day;
cin >> month;
cin >> year;
cout << "Your chosen date is : " << day << "/" << month << "/" << year << endl;
if (day >= 1 && day <= 31 && month >= 1 && month <= 12)
{
nextDay(day, month, year);
}
else
cout << "Invalid date" << endl;
}
Now my question is the following :
If I'm entering 28/02/2016 I'm getting 30/02/2016.
The other question is :
Is there a way to get the date in the DD/MM/YYYY format and then get the DD MM YYYY with a coommand like stoi - I mention that the command is not working for me.
I was trying to get the results like usual if I input 28/02/2016 I should get 29/02/2016 - I know there's another condition to increase the day + 1 but why isn't that skipped ?

Print out dates in four formats

I need to print out dates in four formats when a user enters a month, day and year.
For example if I enter "sept" for month, 17 for day and 1921 for year, it will print out:
1) 9/17/1921
2) September 17,1921
3) 1921-9-17
4) 1921-sep-17
I also do validation where if the number of days is less than 1 or greater than than the number of days for that month and the year cannot be less than 1900 or greater than 2020. If it is, month gets defaulted to "January" day to 1 and year to 2001.
When I enter jan for month 5 for day 2005 for year, I get weird values in my console 1/-858993460/-858993460 and then terminates. But when I enter mar 5 2005 i get
3/5/2005
March2005
ory corruption5
ory corruptionmar-5
I create an instance of Date and call a 3 argument constructor. The 3 argument constructor then calls a validate function which return a boolean. If the return value is false, it will call the default constructor which sets everything to january 1 2001.
//UPDATE:
Changed inital value of int index in date.cpp to -1 instead of NULL. Doing this now calls the print function four times four when I enter "jan" but I still get the weird results
1/5/2005
January2005 //This should be January 5, 2005
ory corruption5
ory corruptionmar-5
Why does the first time print is called all my member variables retain the values, but the 2nd, 3rd, and 4th time, day is missing and shows weird corruption message?
I don't know what is going on but when I also enter an invalid date such as "jan" for month but 36 for days and 2025 for year, the default constructor should set month to January, day to 1 and year to 2001 but I get garbage values
1/-858993460/-858993460
This is the first time print is called then after that it terminates.
//Header
#pragma once
#include <iostream>
#include <string>
using namespace std;
/*Add more constants if needed*/
#ifndef DATE_H
#define DATE_H
enum DateFormat { mdy1, mdy2, ymd1, ymd2 };
const int MIN_YEAR = 1900;
const int MAX_YEAR = 2020;
const string monthStr[] = //alternative: const char monthStr[] [15]=
{ "January", "February", "March", "April", "May", "June",
"July", "August", "September", "October", "November",
"December" };
const string monthStrAbbrev[] = //not strictly necessary, but helpful
{ "jan", "feb", "mar", "apr", "may", "jun",
"jul", "aug", "sep", "oct", "nov",
"dec" };
const int monthDays[] =
{ 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 };
class Date {
private:
string month;
int day, year;
bool validateDate(string, int, int);
Date();
public:
Date(string, int, int);
void print(DateFormat type);
};
#endif // !DATES_H
//Dates.cpp
#include "stdafx.h"
#include <iostream>
#include <algorithm>
#include "date.h"
using std::cout;
using std::cin;
int global;
Date::Date() : month("January"), day(1), year(2001) { cout << "INSIDE CONST" << endl; }
Date::Date(string m, int d, int y)
{
if (!validateDate(m, d, y))
{
cout << "IF FALSE" << endl;
Date();
}
else
{
month = m;
day = d;
year = y;
cout << "MONTH IS :" << month << " DAY IS: " << day << " YEAR IS: " << year << endl;
}
}
bool Date::validateDate(string m, int d, int y)
{
cout << "size is " << sizeof(monthStrAbbrev) / sizeof(monthStrAbbrev[0]) << endl;;
int index = -1;
for (int x = 0; x < 11; x++)
{
string mAbr = monthStr[x].substr (0, 3);
transform(mAbr.begin(), mAbr.end(), mAbr.begin(), (int(*) (int)) tolower);
cout << "Abbr: " << mAbr << endl;
if (m == mAbr)
{
index = x;
global = x;
cout << "x " << x << " global " << global << " Index " << index << endl;
if (d < 1 && d > monthDays[index])
{
cout << "FALSE 1" << endl;
return false;
}
if (y < MIN_YEAR || y > MAX_YEAR)
{
cout << "FALSE 2" << endl;
return false;
}
break;
}
}
if (index == -1)
{
cout << "IF NULL" << endl;
return false;
}
else
{
cout << " IF NOT NULL" << endl;
return true;
}
}
void Date::print(DateFormat type)
{
if (type == mdy1)
{
cout << global + 1 << "/" << day << "/" << year << endl;
}
else if (type == mdy2)
{
cout << monthStr[global] << day + ", " << year << endl;
}
else if (type == ymd1)
{
cout << year + "-" << (global + 1) + "-" << day << endl;
}
else if (type == ymd2)
{
cout << year + "-" << month + "-" << day << endl;
}
}
//Test.cpp
#include "stdafx.h"
#include <iostream>
#include <algorithm>
#include <string>
using namespace std;
#include "date.h"
void setDateValues(string&, int&, int&);
int main()
{
string mth;
int day, yr;
setDateValues(mth, day, yr);
transform(mth.begin(), mth.end(), mth.begin(), (int(*) (int)) tolower);
Date d1(mth, day, yr);
cout << "Date is:\n";
DateFormat type;
type = mdy1;
d1.print(type);
type = mdy2;
d1.print(type);
type = ymd1;
d1.print(type);
type = ymd2;
d1.print(type);
return 0;
}
void setDateValues(string & m, int& d, int& y)
{
cout << "Enter month: ";
cin >> m;
cout << "Enter day: ";
cin >> d;
cout << "Enter year: ";
cin >> y;
}
There is a standard library function for this: strftime().
You give it a date in a struct, and it writes a string. For your four cases, the format strings would be:
1) %m/%d/%Y
2) %B %d, %Y
3) %F
4) %Y-%b-%d

C++ Overload operator - to subtract two objects of the same type

Just trying to follow the book on a self-paced learn C++.
What I have so far is a program that I have created that has an object of Date, which has four parameters. The three parameters that are filled out by the user are, "Month", "Day", and "Year". The fourth parameter is "Old", and that is to store how many days old it is. For that, I have written a function that calculates how many days old it is, and sets it as the forth parameter.
This part works. It calculates how many days old it is.
The book wants me to subtract two objects of type Date and find out the difference between how old they are. For that it specifically requests that I create an overloaded operator of (-), and subtract the two. This is where I am getting a little stuck. The part that I am having issues with is, I believe, the call that is used to access it. I continue to get the error of "ambiguous overload for "operator-' (operand types are 'Date' and 'Date').
It recognizes both objects as Date. Now I just need a little help for the last leg of this.
I have tried using several different things in the header, but perhaps I am implementing them incorrectly.
-friend Date operator - (Date &ob1, Date &ob2);
-Date &operator-();
-Date &operator-(Date);
-Date operator-(Date);
If you can help out with this, it would be wonderful. I'm new, and I've spent over 12 hours on this on question.
Main.cpp
#include <iostream>
#include <time.h>
#include <ctime>
#include "Date.cpp" // Date class definition
using namespace std;
int main() {
unsigned int birthMonth = 0;
unsigned int birthDay = 0;
unsigned int birthYear = 0;
unsigned int dateToMonth = 0;
unsigned int dateToDay = 0;
unsigned int dateToYear = 0;
cout << "Enter birth month (1-12): ";
cin >> birthMonth;
cout << "Enter birth day (1-31): ";
cin >> birthDay;
cout << "Enter birth year (1900 - 2000): ";
cin >> birthYear;
Date birthDate (birthMonth, birthDay, birthYear);
Date tempDate (1, 1, 1, 1);
cout << "To which date would you like to calculate to?\nEnter Day month (1-12): ";
cin >> dateToMonth;
cout << "Enter Day to calculate it to (1-31): ";
cin >> dateToDay;
cout << "Enter Year to calculate it to: ";
cin >> dateToYear;
Date dateTo (dateToMonth, dateToDay, dateToYear);
pastDays(birthDate);
pastDays(dateTo);
cout << "\nHow many days ago is the birth date? " << birthDate.old << endl;
cout << "How many days ago is the secondary date? " << dateTo.old << endl;
// Here is where I get an error "ambiguous overload for "operator-' (operand types are 'Date' and 'Date')"
cout << tempDate = birthDate - dateTo << endl;
cout << tempDate.old;
}
Date.h
#ifndef DATE_H
#define DATE_H
#include <array>
#include <iostream>
class Date
{
friend std::ostream &operator<<( std::ostream &, const Date & );
public:
Date( int m = 1, int d = 1, int y = 1900, int o = 0 ); // default constructor
void setDate( int, int, int, int ); // set month, day, year
// friend Date operator - (Date &ob1, Date &ob2);
Date &operator-(); // Modified Line for Assignment
Date &operator-(Date); // Modified Line for Assignment
// Date operator-(Date);
void pastDays (Date);
static bool leapYear( int ); // is date in a leap year?
unsigned int month;
unsigned int day;
unsigned int year;
int old;
static const std::array< unsigned int, 13 > days; // days per month
}; // end class Date
#endif
Date.cpp
#include <iostream>
#include <string>
#include "Date.h"
#include <time.h>
#include <ctime>
#include <conio.h>
#include "Date.h" // Date class definition
using namespace std;
// initialize static member; one classwide copy
const array< unsigned int, 13 > Date::days = { 0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 };
// Date constructor
Date::Date( int month, int day, int year, int old )
{
setDate( month, day, year, old );
} // end Date constructor
// set month, day and year
void Date::setDate( int mm, int dd, int yy, int old )
{
if ( mm >= 1 && mm <= 12 )
month = mm;
else
throw invalid_argument( "Month must be 1-12" );
if ( yy >= 1900 && yy <= 2100 )
year = yy;
// test for a leap year
// if (month == 1 || month == 3 || month == 5 || month == 7 || month == 8 || month == 10 || month == 12){
// if (dd >= 1 || dd <= 31)
// day == dd;
// }
// if (month == 4 || month == 6 || month == 9 || month == 11){
// if (dd >= 1 || dd <= 30)
// day == dd;
// }
// if (month == 2)
// if ( year % 4 != 0 ) {
// if (dd >= 1 || dd <= 29)
// day == dd;
// }
// if (month == 2)
// if ( year % 4 != 0 ) {
// if (dd >= 1 || dd <= 28)
// day == dd;
// }
// else {
// throw invalid_argument(
// "Day is out of range for current month and year" );
// }
if ( ( month == 2 && leapYear( year ) && dd >= 1 && dd <= 29 ) ||
( dd >= 1 && dd <= days[ month ] ) )
day = dd;
else
throw invalid_argument(
"Day is out of range for current month and year" );
} // end function setDate
void pastDays (Date &entryDay) {
//Creating Today date object
time_t t = time(0);
struct tm * now = localtime(&t);
int currentYear = now -> tm_year + 1900;
int currentMonth = now -> tm_mon + 1;
int currentDay = now -> tm_mday;
int birthMonth = entryDay.month;
int birthDay = entryDay.day;
int birthYear = entryDay.year;
//The variable that will be assigned to the old parameter, which can then be subtracted from another time.
int daysAgo = 0;
entryDay.old = 0;
cout << endl;
cout << "First" << daysAgo << endl;
cout << "BirthMonth: " << birthMonth << endl;
cout << "BirthDay: " << birthDay << endl;
cout << "BirthYear: " << birthYear << endl;
//Lowering days to 1, to make transition between years easier.
// while (birthDay > 1){
// birthDay--;
// daysAgo--;
// }
daysAgo = daysAgo - birthDay;
daysAgo++;
birthDay = 1;
cout << endl;
cout << "Second" << daysAgo << endl;
cout << "BirthMonth: " << birthMonth << endl;
cout << "BirthDay: " << birthDay << endl;
cout << "BirthYear: " << birthYear << endl;
//Lowering months to 1, to make transition between years easier.
while (birthMonth > 1){
if (birthMonth == 1 || birthMonth == 3 || birthMonth == 5 || birthMonth == 7 || birthMonth == 8 || birthMonth == 10 || birthMonth == 12){
birthMonth--;
daysAgo -= 31;
}
if (birthMonth == 4 || birthMonth == 6 || birthMonth == 9 || birthMonth == 11){
birthMonth--;
daysAgo -= 30;
}
if (birthMonth == 2)
if ( currentYear % 400 == 0 ||
( currentYear % 100 != 0 && currentYear % 4 == 0 ) ) {
birthMonth--;
daysAgo -= 29;
}
else {
birthMonth--;
daysAgo -= 28;
}
}
cout << endl;
cout << "Third" << daysAgo << endl;
cout << "BirthMonth: " << birthMonth << endl;
cout << "BirthDay: " << birthDay << endl;
cout << "BirthYear: " << birthYear << endl;
//Incrementing year to current year
while (birthYear < currentYear){
if ( currentYear % 400 == 0 ||
( currentYear % 100 != 0 && currentYear % 4 == 0 ) ) {
daysAgo = daysAgo + 366;
birthYear++;
}
else {
daysAgo = daysAgo + 365;
birthYear++;
}
}
cout << endl;
cout << "Fourth" << daysAgo << endl;
cout << "BirthMonth: " << birthMonth << endl;
cout << "BirthDay: " << birthDay << endl;
cout << "BirthYear: " << birthYear << endl;
// Incrementing to current month
while (birthMonth < currentMonth) {
if (birthMonth == 1 || birthMonth == 3 || birthMonth == 5 || birthMonth == 7 || birthMonth == 8 || birthMonth == 10 || birthMonth == 12){
birthMonth++;
daysAgo += 31;
}
if (birthMonth == 4 || birthMonth == 6 || birthMonth == 9 || birthMonth == 11){
birthMonth++;
daysAgo += 30;
}
if (birthMonth == 2)
if ( currentYear % 400 == 0 ||
( currentYear % 100 != 0 && currentYear % 4 == 0 ) ) {
birthMonth++;
daysAgo += 29;
}
else {
birthMonth++;
daysAgo += 28;
}
}
cout << endl;
cout << "Fifth" << daysAgo << endl;
cout << "BirthMonth: " << birthMonth << endl;
cout << "BirthDay: " << birthDay << endl;
cout << "BirthYear: " << birthYear << endl;
//Incrementing to current day, and adding the days to the daysAgo
while (birthDay < currentDay){
birthDay++;
daysAgo++;
}
cout << endl;
cout << "Sixth" << daysAgo << endl;
cout << "BirthMonth: " << birthMonth << endl;
cout << "BirthDay: " << birthDay << endl;
cout << "BirthYear: " << birthYear << endl;
//Assigning DaysAgo to input parameter.old
entryDay.old = daysAgo;
}
Date operator - (Date &date1, Date &date2)
{
Date temp;
temp.old = date1.old - date2.old;
if(temp.old < 0)
{
temp.old = temp.old * -1;
}
return(temp);
}
//Date operator-(Date birthDate)
////friend Distance operator - (Date &birthDate, Date &today)
// {
//// int birthMonth = birthDate.month;
//// int birthDay = birthDate.day;
//// int birthYear = birthDate.year;
//// int birthOld = 0;
//// Date temp (birthDate.month, birthDate.day, birthDate.year, birthDate.old);
//
//// pastDays(today);
//// pastDays(birthDate);
//
//// int currentMonth = today.month;
//// int currentDay = today.day;
//// int currentYear = today.year;
//
//// int date1 = pastDays(today);
//// int date2 = pastDays(birthDate);
// Date temp (birthDate.month, birthDate.day, birthDate.year);
//
//// int month, int day, int year, int old
//// temp.month = this -> month;
//// temp.month = this -> day;
//// temp.month = this -> year;
//// Date temp = *this;
// cout << temp.old;
//
// temp.old = *this -> old - birthDate.old;
// //Here I get "Error: Invalid use of 'this' in non-member function;
//
// return(temp);
//}
bool Date::leapYear( int testYear )
{
if ( testYear % 400 == 0 ||
( testYear % 100 != 0 && testYear % 4 == 0 ) )
return true; // a leap year
else
return false; // not a leap year
} // end function leapYear
// overloaded output operator
ostream &operator<<( ostream &output, const Date &d )
{
static string monthName[ 13 ] = { "", "January", "February",
"March", "April", "May", "June", "July", "August",
"September", "October", "November", "December" };
output << monthName[ d.month ] << ' ' << d.day << ", " << d.year;
return output; // enables cascading
} // end function operator<<
Define your binary arithmetic operators (e.g -) using your compound assignment operators(e.g -=). You may want to take a look at this binary arithmetic operator reference:
Date& operator-=(const X& rhs) {
/* subtraction of rhs to *this takes place here */
this->year - rhs.year; // This is the easy one
/* Here you will have to play around with this->month and this->day */
return *this; // return the result by reference
}
friend Date operator-(Date lhs, const Date& rhs) {
lhs -= rhs; // use compound assignment
return lhs; // return the result by value
}
main.cpp
#include <iostream>
#include <time.h>
#include <ctime>
#include "Date.cpp" // Date class definition
using namespace std;
int main() {
unsigned int birthMonth = 0;
unsigned int birthDay = 0;
unsigned int birthYear = 0;
unsigned int dateToMonth = 0;
unsigned int dateToDay = 0;
unsigned int dateToYear = 0;
cout << "Enter birth month (1-12): ";
cin >> birthMonth;
cout << "Enter birth day (1-31): ";
cin >> birthDay;
cout << "Enter birth year (1900 - 2000): ";
cin >> birthYear;
Date birthDate (birthMonth, birthDay, birthYear);
Date tempDate (1, 1, 1, 1);
cout << "To which date would you like to calculate to?\nEnter Day month (1-12): ";
cin >> dateToMonth;
cout << "Enter Day to calculate it to (1-31): ";
cin >> dateToDay;
cout << "Enter Year to calculate it to: ";
cin >> dateToYear;
Date dateTo (dateToMonth, dateToDay, dateToYear);
pastDays(birthDate);
pastDays(dateTo);
cout << "\nHow many days ago is the birth date? " << birthDate.old << endl;
cout << "How many days ago is the secondary date? " << dateTo.old << endl;
tempDate = birthDate - dateTo;
cout << tempDate.old;
}
Date.h
#ifndef DATE_H
#define DATE_H
#include <array>
#include <iostream>
class Date
{
friend std::ostream &operator<<( std::ostream &, const Date & );
// friend Date operator-(Date, Date);
public:
Date( int m = 1, int d = 1, int y = 1900, int o = 0 ); // default constructor
void setDate( int, int, int, int ); // set month, day, year
// friend Date operator-(Date, Date);
Date operator-(); // Modified Line for Assignment
Date operator-(Date); // Modified Line for Assignment
// Date operator-(Date);
void pastDays (Date);
static bool leapYear( int ); // is date in a leap year?
unsigned int month;
unsigned int day;
unsigned int year;
int old;
static const std::array< unsigned int, 13 > days; // days per month
}; // end class Date
#endif
Date.cpp
#include <iostream>
#include <string>
#include "Date.h"
#include <time.h>
#include <ctime>
#include <conio.h>
#include "Date.h" // Date class definition
using namespace std;
// initialize static member; one classwide copy
const array< unsigned int, 13 > Date::days = { 0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 };
// Date constructor
Date::Date( int month, int day, int year, int old )
{
setDate( month, day, year, old );
} // end Date constructor
// set month, day and year
void Date::setDate( int mm, int dd, int yy, int old )
{
if ( mm >= 1 && mm <= 12 )
month = mm;
else
throw invalid_argument( "Month must be 1-12" );
if ( yy >= 1900 && yy <= 2100 )
year = yy;
if ( ( month == 2 && leapYear( year ) && dd >= 1 && dd <= 29 ) ||
( dd >= 1 && dd <= days[ month ] ) )
day = dd;
else
throw invalid_argument(
"Day is out of range for current month and year" );
} // end function setDate
void pastDays (Date &entryDay) {
//Creating Today date object
time_t t = time(0);
struct tm * now = localtime(&t);
int currentYear = now -> tm_year + 1900;
int currentMonth = now -> tm_mon + 1;
int currentDay = now -> tm_mday;
int birthMonth = entryDay.month;
int birthDay = entryDay.day;
int birthYear = entryDay.year;
//The variable that will be assigned to the old parameter, which can then be subtracted from another time.
int daysAgo = 0;
entryDay.old = 0;
cout << endl;
cout << "First" << daysAgo << endl;
cout << "BirthMonth: " << birthMonth << endl;
cout << "BirthDay: " << birthDay << endl;
cout << "BirthYear: " << birthYear << endl;
//Lowering days to 1, to make transition between years easier.
// while (birthDay > 1){
// birthDay--;
// daysAgo--;
// }
daysAgo = daysAgo - birthDay;
daysAgo++;
birthDay = 1;
cout << endl;
cout << "Second" << daysAgo << endl;
cout << "BirthMonth: " << birthMonth << endl;
cout << "BirthDay: " << birthDay << endl;
cout << "BirthYear: " << birthYear << endl;
//Lowering months to 1, to make transition between years easier.
while (birthMonth > 1){
if (birthMonth == 1 || birthMonth == 3 || birthMonth == 5 || birthMonth == 7 || birthMonth == 8 || birthMonth == 10 || birthMonth == 12){
birthMonth--;
daysAgo -= 31;
}
if (birthMonth == 4 || birthMonth == 6 || birthMonth == 9 || birthMonth == 11){
birthMonth--;
daysAgo -= 30;
}
if (birthMonth == 2)
if ( currentYear % 400 == 0 ||
( currentYear % 100 != 0 && currentYear % 4 == 0 ) ) {
birthMonth--;
daysAgo -= 29;
}
else {
birthMonth--;
daysAgo -= 28;
}
}
cout << endl;
cout << "Third" << daysAgo << endl;
cout << "BirthMonth: " << birthMonth << endl;
cout << "BirthDay: " << birthDay << endl;
cout << "BirthYear: " << birthYear << endl;
//Incrementing year to current year
while (birthYear < currentYear){
if ( currentYear % 400 == 0 ||
( currentYear % 100 != 0 && currentYear % 4 == 0 ) ) {
daysAgo = daysAgo + 366;
birthYear++;
}
else {
daysAgo = daysAgo + 365;
birthYear++;
}
}
cout << endl;
cout << "Fourth" << daysAgo << endl;
cout << "BirthMonth: " << birthMonth << endl;
cout << "BirthDay: " << birthDay << endl;
cout << "BirthYear: " << birthYear << endl;
// Incrementing to current month
while (birthMonth < currentMonth) {
if (birthMonth == 1 || birthMonth == 3 || birthMonth == 5 || birthMonth == 7 || birthMonth == 8 || birthMonth == 10 || birthMonth == 12){
birthMonth++;
daysAgo += 31;
}
if (birthMonth == 4 || birthMonth == 6 || birthMonth == 9 || birthMonth == 11){
birthMonth++;
daysAgo += 30;
}
if (birthMonth == 2)
if ( currentYear % 400 == 0 ||
( currentYear % 100 != 0 && currentYear % 4 == 0 ) ) {
birthMonth++;
daysAgo += 29;
}
else {
birthMonth++;
daysAgo += 28;
}
}
cout << endl;
cout << "Fifth" << daysAgo << endl;
cout << "BirthMonth: " << birthMonth << endl;
cout << "BirthDay: " << birthDay << endl;
cout << "BirthYear: " << birthYear << endl;
//Incrementing to current day, and adding the days to the daysAgo
while (birthDay < currentDay){
birthDay++;
daysAgo++;
}
cout << endl;
cout << "Sixth" << daysAgo << endl;
cout << "BirthMonth: " << birthMonth << endl;
cout << "BirthDay: " << birthDay << endl;
cout << "BirthYear: " << birthYear << endl;
//Assigning DaysAgo to input parameter.old
entryDay.old = daysAgo;
}
bool Date::leapYear( int testYear )
{
if ( testYear % 400 == 0 ||
( testYear % 100 != 0 && testYear % 4 == 0 ) )
return true; // a leap year
else
return false; // not a leap year
} // end function leapYear
// overloaded output operator
ostream &operator<<( ostream &output, const Date &d )
{
static string monthName[ 13 ] = { "", "January", "February",
"March", "April", "May", "June", "July", "August",
"September", "October", "November", "December" };
output << monthName[ d.month ] << ' ' << d.day << ", " << d.year;
return output; // enables cascading
} // end function operator<<
Date Date::operator-(Date rhs) {
//lhs -= rhs; // use compound assignment
//return lhs; // return the result by value
Date n = *this;
n.old -= rhs.old;
return n;
}

Can I compare a char* (month) with a string (February)? If not, how can I go about doing this?

I want the program to work so that I can turn any worded month to its equivalent number.
#include <iostream>
using namespace std;
int main()
{
char month[20];
int INT_month;
cout << "Enter a month: (ex. January, February)";
cin >> month; // Let's say the input is February
if (month == "February")
INT_month = 2;
cout << "The month in its' integral form is " << INT_month << endl;
// INT_month = 2130567168 // WHY DOES IT DO THIS????
return 0;
}
One way to do it is creating a vector of month names, and using the look-up index plus one as the month number:
vector<string> months = {
"january", "february", "march", ...
};
string search = "march";
auto pos = find(months.begin(), months.end(), search);
if (pos != months.end()) {
cout << "Month number: " << distance(months.begin(), pos) + 1 << endl;
} else {
cerr << "Not found" << endl;
}
This prints 3 (demo on ideone).