This is a small beginner project for my self-taught C++ course. It's a movie recommender in which the user selects a number, tied to a genre, and the program reads through a text file and selects a random title for the user. As a beginner my first instinct was to use IF statements but it was way too long. I tried using a SWITCH statement to try to shorten it but it's still the same lenght (although much more organized and easier to read). Any other suggestion for shortening my code, I know I can do better.
One more possibility, a slightly different approach. Store all the different filenames in an array of strings. Then instead of using a switch statement, simply retrieve the corresponding filename from the array and then proceed as before.
void print_whatever(constchar *filename) {
...
}
int main() {
...
//create array with all the file names (in order)
constchar* filenames[] = {
"romance.txt",
"comedy.txt",
...
};
//bounds checking: number is between 1 and 5 (inclusive)
if( 1 <= number && number <= 5 )
//"number is 1" corresponds to "array element 0", etc...;
print_whatever( filenames[number - 1] );
else
//bad input, it's out of bounds
cout << "Type a number between 1 and 5." << endl;
...
}