variables & if_statement

Some advice on how to be more efficient would help thank you!!


using namespace std;

int main(){

int year_born;
string month;
int c_year = 2019;
int l_year = 2018;

cout << "What year were you born: "; cin >> year_born;
cout << endl;

cout << "What month were you born(Please capatalize the first letter): "; cin >> month;
cout << endl;

if(month == "January" || month == "February" || month == "March"){

cout <<"You are " << (c_year) - (year_born)<< " years old." << endl;


cout << "You are " << (l_year) - (year_born) << " years old." << endl;

return 0;
You mean, so you don't have to edit and recompile the program next week to include April in your list of months?
Use this to find out the current year and month.

Some advice on how to be more efficient

1. PLEASE learn to use code tags, it makes reading (and commenting on) your code MUCH easier.

You can edit your post and add code tags.

2. Don't ask the user to enter a string, use an int (1-12). Less to type, easier to compare. If the user types even one letter incorrectly for the month, it won't match.

3. To expand on salem c's recommendation, <ctime> includes a tm structure, holding a calendar date and time broken down into its components. This makes calculating a time duration like a user's current age MUCH easier.

4. Calculating the user's current age: subtract birth_year from current_year, subtracting one year from that total if the current_month is less than the birth_month.
int age = current_year - birth_year - ((current_month < birth_month) ? 1 : 0);
Last edited on
Hey Furry Guy is that a tertiary statement if so I have no idea how to use them.
It is the ternary operator AKA the conditional operator, and no better time to begin learning than now. It is very efficient when used properly.

<test condition> ? <true result> : <false result> is a compact way to do an if/else block.

What was done in one statement would require multiple statements:

1. the original age definition int age = current_year - birth_year;

2. with an ugly if/else block to check if the current_month is less than the birth_month.

int age = current_year - birth year;

if (current_month < birth_month)
   age -= 1;
   are -= 0;

Since the condition when the current month equals or is greater than the birth month doesn't actually change the age variable you could skip else clause block.
Last edited on
Registered users can post here. Sign in or register to post.