matt
matt

Reputation: 33

function in c++ that takes the month number and prints the number of days for the month

the code worked before I added in the part where if the user enters in a number higher then 12 I want it to say "not a number for a month." im trying to get if and else to work but it just always stops the program im also new to programming sorry for bad format. Any help is good. thanks.

#include <iostream>
using namespace std;

int main()
{

int month = 0;
int days;

cout << "Month: ";
cin >> month;

if (month != 1 || month != 2 || month != 3 || month != 4 || month != 5 || 
    month != 6 || month != 7 || month != 8 || month != 9 || month != 10 || 
    month != 11 || month != 12 ) {

cout<<"not a number for a month";

return 0;

}


if (month == 4 || month == 6 || month == 9 || month == 11)
    days = 30;

else 

days = 31;

cout << days;

return 0;
}

Upvotes: 0

Views: 3171

Answers (1)

Bathsheba
Bathsheba

Reputation: 234845

Replace that utterly evil if conditional with

if (month < 1 || month > 12){

Besides being ghastly, you are using || in error: your conditional is always true. You needed &&.

Then fix the special case for month == 2. At that point you'll need to know the year.

As a rule of thumb: if you find yourself writing very tedious code, then there is probably a simpler way of expressing your intent.

Upvotes: 5

Related Questions