C++ program for checking whether the input is a leap year - c++

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

Related

How to make one function's if/else condition control other function in a structure?

We got an assignment where we were supposed to make a birthday wisher. Now whenever the input for month date and year is invalid ( such as negative or zero or beyond the range of months and days) the program should not proceed forth. How to make it do that?
#include <iostream>
using namespace std;
struct birthday_wisher {
int date;
int month;
int year;
int todaysdatedd,todaysdatemm;
void getdob() {
cout << "enter your date of birth (dd/mm/yy) " << endl;
cin >> date >> month >> year;
if ((todaysdatedd > 0 && todaysdatedd <= 31) && (todaysdatemm > 0 && todaysdatemm <= 12) && year>0 )
{
cout << "you have entered a valid date " << endl;
}
else
{
cout << "invalid date/ month\n";
}
}
void gettodaysdate() {
cout << "enter today's date (dd/mm)\n";
cin >> todaysdatedd >> todaysdatemm;
if ((todaysdatedd>0 && todaysdatedd<=31) && (todaysdatemm>0 && todaysdatemm<=12))
{
cout << "you have entered a valid date" << endl;
}
else
{
cout << "invalid date/ month";
}
}
void check() {
if (month == todaysdatemm) {
if (date == todaysdatedd)
{
cout << "happy birthday!";
}
}
else
{
cout << "your birthday is not today ;-;\n";
}
}
};
int main()
{
birthday_wisher b1;
b1.getdob();
b1.gettodaysdate();
b1.check();
}
You got a few options.
The brute option: Put exit(int exitCode) after the check fails. This will immediately exit the program e.g.
if (IsNotAValidDate())
{
exit(1);
}
The better option: Make getdob to return bool and make the program peacefully exit if the condition fails.
bool getdob() {
// You might want to check also for 31/30 day months and for February as here are bugs
cout << "enter your date of birth (dd/mm/yy) " << endl;
cin >> date >> month >> year;
return (todaysdatedd > 0 && todaysdatedd <= 31) && (todaysdatemm > 0 && todaysdatemm <= 12) && year>0;
}
int main()
{
birthday_wisher b1;
if (b1.getdob())
{
b1.gettodaysdate();
b1.check();
}
else
{
std::cout << "Invalid date provided\n";
}
return 0;
}

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

Issues with precompiled headers?

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 :(

Leap year program doesn't seem to run

Question - A year with 366 days is called a leap year. A year is a leap year if it is divisible by four (for example, 1980), except that it is not a leap year if it is divisible by 100 (for example, 1900); however, it is a leap year if it is divisible by 400 (for example, 2000). There were no exceptions before the introduction of the Gregorian calendar on October 15, 1582. Write a program that asks the user for a year and computes whether that year is a leap year.
This is what I have so far, and the program doesn't seem to run for years greater than 1582. Could someone help me out why? Thanks a bunch
using namespace std;
int main()
{
cout<< "Pleas enter a year: " <<endl;
int year = 0;
cin >> year;
if (year <= 1581)
{
if (year % 4 == 0)
{
cout << "It's a leap year, wow! " << endl;
}
else
{
cout << "It's not a leap year " << endl;
}
}
else if (year > 1581)
{
if (year % 4 == 0)
{
if (year % 100 == 0)
{
cout<< "It is not a leap year " << endl;
}
else if (year % 400 == 0)
{
cout<< "It is a leap year, Wow!" << endl;
}
}
}
else
{
cout<< "You entered a wrong year number "<< year<< endl;
}
return 0;
}
You are making it very complex. I don't think you need to care about whether the year is greater than 1582 or not (for a 4 digit number) provided that a leap year is one which is:
• Divisible by 400
OR
• NOT divisible by 100 AND divisible by 4.
Using unnecessary nested ifs can make your code long and error prone. Try this method:
#include<iostream.h>
int main(){
int y=0;
cout << "Enter a year\n";
cin >> y;
cout <<"\n"<<y;
if(y%400==0 || (y%100!=0 && y%4==0))
cout <<" is a leap year";
else
cout <<" is not a leap year";
return 0;
}
Without check if year > 1582
#include<iostream>
using namespace std;
int main()
{
int year;
cout<< "Please enter a year: " <<endl;
cin >> year;
if( year%25 && !(year&3) || !(year&15) )
cout << "It's a leap year!" << endl;
else
cout << "It's not a leap year!" << endl;
return 0;
}
You are missing a number of cases in the handling of years after 1581.
printing "Not leap year" unless (year % 4 == 0)
The third case where a year divisible by 4 is neither divisible by 100 nor 400
It as simple as you have just not written any code that is run when year is 2004, for example.
You are missing 2 else statement
using namespace std;
int main()
{
cout<< "Pleas enter a year: " <<endl;
int year = 0;
cin >> year;
if (year <= 1581)
{
if (year % 4 == 0)
{
cout << "It's a leap year, wow! " << endl;
}
else
{
cout << "It's not a leap year " << endl;
}
}
else if (year > 1581)
{
if (year % 4 == 0)
{
if (year % 100 == 0)
{
cout<< "It is not a leap year " << endl;
}
else if (year % 400 == 0)
{
cout<< "It is a leap year, Wow!" << endl;
}
// <----------- Here you are missing an else
}
// <----------- Here you are missing an else
}
else
{
cout<< "You entered a wrong year number "<< year<< endl;
}
return 0;
}
I suggest
if ( ((year % 400) == 0)
|| ( ((year % 4) == 0) // or (year & 0x3) == 0
&& ( (year <= 1581)
|| ((year % 100) != 0) )))
cout << "It's a leap year, wow! " << endl;
else
cout << "It's not a leap year " << endl;
or
if ( ((year % 4) == 0) // or year & 0x3 == 0
&& ( (year <= 1581)
|| ((year % 100) != 0)
|| ((year % 400) == 0) ) )
cout << "It's a leap year, wow! " << endl;
else
cout << "It's not a leap year " << endl;
It’s a good idea to simplify your conditionals. A general method for this is to convert to a normal form—either conjunctive or disjunctive—and put the tests that are most likely to short-circuit, first. For simple cases such as this, you can just eyeball it.
In this case, conjuctive normal form is extremely simple:
year%4 == 0 &&
( year < 1582 || year%100 != 0 || year%400 == 0 )
That is, the year is divisible by four and any of the three conditions of the Gregorian calendar reform do not hold. Since the first && term that is false, and the first || term that is true, short-circuit the expression, we want to put the clauses that are most likely to short-circuit, first.
Note that you can code-golf year%100 != 0 to year%100 inside a conditional expression, and year%2000 == 0 to !(year%2000), if you find that easier to read.
It makes sense to move this to a helper function. We can mark it constexpr to give the compiler a hint that it can calculate whether constants are leap years or not at compile-time.
I don't like to post complete answers to what look like homework problems, but that ship has sailed.
#include <cstdlib>
#include <iostream>
using std::cin;
using std::cout;
constexpr bool is_leap(const int year)
{
// Conjunctive normal form:
return ( year%4 == 0 &&
( year < 1582 || year%100 != 0 || year%400 == 0 ) );
}
int main()
{
int year = 0; // Used only within the body of the loop that sets it.
while (cin >> year)
cout << year
<< ( is_leap(year) ? " is a leap year.\n"
: " is not a leap year.\n" );
return EXIT_SUCCESS;
}
Even for a trivial program such as this, there’s a design decision worth thinking about: do we declare int year; uninitialized, or initialize it to a bad value such as int year = 0;? In this case, it’s safe either way, because year is only used inside the body of the loop that sets it. If we don’t initialize it, though, we might later refactor the code to use year outside the loop, and then there might be a code path where year is used before it’s initialized (causing undefined behavior!) On the other hand, if we do initialize year, we might prevent the compiler from noticing that there’s a path where it’s used before it was initialized for real. I personally prefer to initialize to an invalid value and assert that it has been updated before use.
Or you can simply write the following program:
#include<iostream>
using namespace std;
int main()
{
int year;
cout << "Enter year: ";
cin >> year;
if ((year % 4 == 0 && year % 100 != 0) || year % 400 == 0){
cout << "It is a leap year" << endl;
}
else{
cout << "It is not a leap year" << endl;
}
return 0;
}

Why is my program crashing when it reads a hyphen from a string? [closed]

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');