Hey all, I think that I'm finally getting the hang of this C++ thing.
So right now, I'm writing a program that takes user input and outputs the date in three different formats using classes, member functions, constructors, and the like:
9/25/2011
September 25, 2011
25 September 2011
I've got the majority of this program written, but I can't for the life of me get the month number (numMonth) to select the proper month.
Initially I tried creating a giant if statement but the complier just spat out error after error.
Do you mean you don't know how to get "September" from 9?
I suggest using an array:
1 2 3
constchar* month_list[] = {"Jan", "Feb", "etc."};
int current_month = 1;//1 to 12
constchar* current_month_name = month_list[current_month-1];//Now this points to "Jan"
#include "stdafx.h"
#include <iostream>
#include <stdlib.h>
#include <stdio.h>
#include <string>
usingnamespace std;
string Months[]={"January","February","March","April","May","June","July","August","September","October","November","December"};
int main(void)
{
int m;
cout << "What month were you born? (1-12)";
cin >> m;
cout << "So, you were born in the month of " << Months[m-1]<< "\n\n"; // subtract 1 from input, since arrays start at 0
return 0;
}
Originally posted by Hamsterman
Do you mean you don't know how to get "September" from 9?
I suggest using an array:
1 2 3
constchar* month_list[] = {"Jan", "Feb", "etc."};
int current_month = 1;//1 to 12
constchar* current_month_name = month_list[current_month-1];//Now this points to "Jan"
The thing is... we're not supposed to use arrays because its not in the chapters that we supposed to have read.
The first thing that I thought was to use an array, but I can't.
Originally posted by firedraco
That seems fine to me. Only thing I would change is remove "alphMonth" and just return the month name directly since you can't use arrays.
the problem, at least from my limited understanding, is that I need this function, getMonthName to return the name of the month to a variable that can then be printed out by the main function.
Whether you immediately return it, or use a temp variable first, doesn't matter. The following two functions are the exact same, except that the latter one is more efficient.
1 2 3 4 5 6 7 8
int gimmeFive() {
int i = 5;
return i;
}
int gimmeFive() {
return 5;
}
I even think you can drop the "break" statement after return in a switch(), since return immediately ends the function.
To return the month name, use something like this.
1 2 3 4 5 6 7 8 9
int m;
string month;
do
{
cout << "What month were you born? (1-12) ";
cin >> m;
month = getMonthName(m);
cout << "So, you were born in the month of " << month << ".\n\n";
} while (m < 1 || m > 12);
And under getMonthName
1 2 3 4 5
.....
case 12:
return"December";
default:
return"WHAT?? !!"; // default for any input over/under 1 to 12