Personally I believe the best way is to keep the letters and strings away from the code. Make a table similar to this:
const char * month_names[] = {
"jan", "feb", "mar", "apr", "may", "jun", "jul", "aug",
"sep", "oct", "nov", "dec", NULL };
Then make a function like this:
int month_number_from_name(con
{
int i = 0;
while (i < 12) {
if (strcasecmp(month_names[i]
break;
++i;
}
if (i == 12) {
// 'name' wasn't recognized as a month name.
return 0;
} else {
return i + 1; // to get month number in range 1..12
}
}
This is the "best" way to solve this problem, it is also easy to expand on it if you need more advanced features. For example you would like to be able to understand several languages, in this case several strings may map to the same month number.
Make a struct:
struct entry {
const char * name;
int id;
};
entry month_table[] = {
{ "jan", 1 }, { "feb", 2 }, ... { NULL, 0 } };
int month_number_from_name(con
{
entry * p = month_table;
while (p -> name != 0) {
if (strcasecmp(p -> name, name) == 0)
return p -> id;
++p;
}
return 0;
}
If you want to allow the user to abbreviate the month name as long as it stays unique, you can instead of strcasecmp use strncasecmp and compare the number of characters the user provided. In this case you should probably make a special check for length being at least 2 chars and when finding a match you shouldn't just return it but rather save it and then if you didn't find a conflicting match you return it, if you found an exact match you return that but if you found 2 partial matches that both matched you should return error.
Either way, this is the most flexible solution to the problem.
Alf
Main Topics
Browse All Topics





by: KnightMPosted on 2003-01-26 at 22:20:37ID: 7819073
I'm not sure if this is quite what you were looking for, but I hope that it helps anyway. The following code allows for the user to enter in the full name of the month if they wish.
#include <iostream>
#include <string>
using namespace std;
int month;
int mont(char a, char b, char c)
{
if (a == 'J' || a == 'j')
{
if (b == 'A' || b == 'a') return 1;
else {
if (c == 'N' || c == 'n') return 6;
else return 7;
}
}
if (a == 'F' || a == 'f') return 2;
if (a == 'M' || a == 'm')
{
if (c == 'R' || c == 'r') return 3;
else return 5;
}
if (a == 'A' || a == 'a')
{
if (b == 'P' || b == 'p') return 4;
else return 8;
}
if (a == 'S' || a == 's') return 9;
if (a == 'O' || a == 'o') return 10;
if (a == 'N' || a == 'n') return 11;
if (a == 'D' || a == 'd') return 12;
//On error, return 0
return 0;
}
void getmonth(istream &ins)
{
string mon;
cout << "Enter the first three letters of the month: ";
ins >> mon;
month = mont(mon[0], mon[1], mon[2]);
if (month != 0) cout << "\n" << month << "\n";
else cout << "ERROR!";
}
void main()
{
getmonth(cin);
}