I've been thinking about how to create a robust function that parses the command line arguments for valid filenames. I came up with a while-switch construct because that allows me to reduce redundancy (no break-statement at the end of case 2).
As I am pretty new to programming, I can't really tell the quality of this code. Can you think of a way to improve this code in robustness as well as in elegance?
void spellchecker::openFiles(int argc, char* argv[]) {
bool filesOpen = false;
std::string dict_filename;
std::string text_filename;
while (filesOpen == false) {
switch (argc) {
case 2:
printf("You already entered the name of the dictionary file as \"%s\". Is this correct? (y/n): ", argv[1]);
if (std::cin.get() == 'y') {
printf("Ok, please enter the name of the text file you want to check: ");
std::cin >> text_filename;
break;
}
/* no break so user can enter both filenames*/
default:
case 1:
printf("Please enter the name of the dictionary: ");
std::cin >> dict_filename;
printf("Please enter the name of the text file to check: ");
std::cin >> text_filename;
break;
case 3:
dict_filename = argv[1];
text_filename = argv[2];
break;
} // switch
if (!dict_file.is_open()) {
dict_file.open(dict_filename.c_str(), std::ifstream::in);
}
if (!text_file.is_open()) {
text_file.open(text_filename.c_str(), std::ifstream::in);
}
if (dict_file.good() && text_file.good()) {
filesOpen = true;
}
} // while
}