patterncppMinor
Input stream for console menu
Viewed 0 times
streaminputmenuforconsole
Problem
I've written a simple numeric menu which displays in the console. When the user types in '1', something happens. When the user hits ENTER, I clear the whole output except for the menu itself. When the user types in '5', the program ends.
However, the code got ugly. It's full of
How could I improve this code?
However, the code got ugly. It's full of
cin.get()s, couts, and other stuff.int main()
{
using namespace std;
node *root = NULL;
char ch = '0';
while(ch != '5')
{
cout > ch; cin.get();
switch(ch)
{
case '1': case '3':
{
vector numbers;
string line;
cout > current) numbers.push_back(current);
(ch == '1') ? insert(root, numbers) : remove(root, numbers);
cout > name;
buildTree(root, loadNumbersFromFile(name));
exportTreeToFile(root, name);
std::cout << "\nData has been exported.\n\n";
cin.get(); cin.get();
break;
}
}
system("cls");
}
exit(EXIT_SUCCESS);
}How could I improve this code?
Solution
-
-
Using namespace std: I've already mentioned this in the comments. Although it's not a huge deal for small programs such as this, it's still not a good habit to develop.-
While loop: Put std::cin
-
std::cin: You don't need std::cin.get() alongside std::cin >>. Just use std::cin >> for char inputs. However, you'll need a std::cin.ignore() before each getline since you're doing a char input (menu prompt) before a std::string input in your cases. For case 4, keep a consistent getline for the filename input and put an ignore before it.
Also, you don't need any cins after your cases since your while loop will always ask for an input for ch. I do see what you're doing with your outputs in your cases, but you don't need to do that. Just let your cases do their things and go straight to the menu and/or prompt again.
-
Filename input: You should provide validation for the filename input. If the user enters in invalid filename, what should happen? Consider implementing a loop asking the user for a valid filename as long as such file cannot be opened. With the provided code here, it's a bit tough for me to give a piece of example code for that.
-
Functions: You could nicely organize your switch statements by putting the body code into functions. Just name them as they appear in your menu. Call each one in your respective cases, along with the breaks. Also, it might be better to have separate procedures for add/remove.
-
Exit: You don't really need exit(EXIT_SUCCESS) here if the program will always terminate successfully. You also don't need system("cls"), so just leave it out. If you're doing that just to prevent the menu from appearing before each prompt, just pt it before the while` loop.Code Snippets
(ch == '1' || ch == '2' || ch == '3' || ch == '4')Context
StackExchange Code Review Q#25293, answer score: 2
Revisions (0)
No revisions yet.