So I am trying to implement a menu in a program I am writing. My goal is to have zero errors when collecting user input. So I thought the best way to validate was to capture the input as a string and then test against it and prompt for input again until it is valid.
As far as I can tell, my code works as I want it to. BUT, is this the best way to go about this? Almost every example online uses char or int for the input, are there benefits to this?. I feel like I made it more complex than it needed to be. As a beginner, any suggestions would be appreciated.
#include <iostream>
#include <string>
using namespace std;
string GetInput()
{
string s = "";
cout << ">> ";
getline(cin, s);
return s;
}
void mainMenu() {
cout << "Select an option" << endl;
cout << "1. Add Entry" << endl;
cout << "2. Edit Entry" << endl;
cout << "Q. Quit" << endl;
string input = GetInput();
while (!(input.find_first_not_of("12qQ") == string::npos) || input.empty())
{
input = GetInput();
}
if (input == "1") {
cout << "Add Entry" << endl;
//AddEntry();
}
else if (input == "2") {
cout << "Edit Entry" << endl;
}
else {
cout << "Quit" << endl;
}
}
int main() {
cout << "===================================================" << endl;
cout << "| Secure Database |" << endl;
cout << "===================================================" << endl << endl;
mainMenu();
return 0;
}