The following code simply prompts the user to choose from a menu, and then it displays the choice made by that user.
It only accepts input consisting of a single digit between 1 and 6, inclusive. Anything else will be considered as being invalid.
Questions
While it considers Ctrl-D as an invalid choice, should it be handled differently? If so, how?
It takes user input as an
int
. Would you suggest taking it as astring
instead, and then use eitherstoi
orstringstream
to convert it to anint
?Can it be re-written in a more elegant and concise way?
Do you see any potential issues?
Any comments?
Source Code
#include <iostream>
#include <limits>
int getChoice()
{
std::cout << "Main Menu\n"
<< "-------------------\n"
<< "1. Add record\n"
<< "2. Edit record\n"
<< "3. Delete record\n"
<< "4. View record\n"
<< "5. View all records\n"
<< "6. Exit\n";
bool isValid;
int choice;
do
{
isValid = true;
std::cout << "Enter choice: ";
std::cin >> choice;
if (std::cin.fail())
{
if (std::cin.eof())
{
std::cin.clear();
}
else
{
std::cin.clear();
std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
}
isValid = false;
}
else
{
std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
if (std::cin.gcount() > 1)
{
isValid = false;
}
else if (choice < 1 || choice > 6)
{
isValid = false;
}
}
if (!isValid)
{
std::cout << "Invalid choice\n";
}
} while (!isValid);
return choice;
}
int main()
{
int choice;
choice = getChoice();
std::cout << "User chose option " << choice << std::endl;
return 0;
}
Input and Results
Main Menu
-------------------
1. Add record
2. Edit record
3. Delete record
4. View record
5. View all records
6. Exit
Enter choice: x
Invalid choice
Enter choice: 8
Invalid choice
Enter choice: 2x
Invalid choice
Enter choice: x2
Invalid choice
Enter choice: xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
Invalid choice
Enter choice: 888888888888888888888888888888888888888888888888888888888888888888888888888
Invalid choice
Enter choice: Invalid choice // Ctrl-D entered here
Enter choice: ^Z
[1]+ Stopped ./getchoice_cpp