Limiting keyboard input

My program has a basic menu with options a-h, that leads to other menus and I was wondering if there is a way to limit the the user input to one character so the first input doesn't mess with the following menus.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
  cout << endl << endl << "			MATH SKILLS PRACTICE PROGRAM"<<endl;
	cout << endl << "	Hello, and welcome to the Math Skills Practice Program.";
	cout << endl << "	This program allows you to practice you math skills";
	cout << endl << "	Choose what you want to practice in the menu shown below" << endl;
	cout << endl;
	cout << endl << "	-----------------------------------------------------------";
	cout << endl << "	a.	Addition		(X+Y)";
	cout << endl << "	b.	Subtraction		(X-Y)";
	cout << endl << "	c.	Multiplication		(X*Y)";
	cout << endl << "	d.	Division		(X/Y)";
	cout << endl << "	e.	Roots			(Square Root, Cube Root)";
	cout << endl << "	f.	Powers			(X-Squared, X-Cubed)";
	cout << endl << "	g.	Geometry		(Area, Perimeter)";
	cout << endl << "	h.	Quit the Program";
	cout << endl << "	-----------------------------------------------------------" << endl;
	cout << endl << "	Choose on of the above (a-h):  " << endl;
	cout << endl << "	-----------------------------------------------------------" << endl;
	cout << endl << "	Your choice: ";
	cin >> main_choice;
	
This is a little long, and there are probably better ways to do this, but you could do something like if else statements in a while loop.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
while(1){
if(main_choice != "a"&& main_choice != "b" && main_choice != "c"&& main_choice != "d"&& main_choice != "e"&& main_choice != "f"&& main_choice != "g"&& main_choice != "h")
{
cout << "Invalid comand" << endl;
cout << "Your Choice: ";
cin >> main_choice;
}
else if (main_choice == "a")
{ 
// do whatever a is suppose to do
}
else if (main_choice == "b")
{
// You get the point right?
}

}


etc.
Last edited on
For a clean and cross-platform solution I came up with this code:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
#include <iostream>
#include <climits>
using std::cout;
using std::endl;
using std::cin;


int main(int argc, char **argv) {
    // store a single character
    char character;
    // get a single character from the input stream
    cin >> character;
    // clear everything else from the input buffer
    cin.ignore(INT_MAX, '\n');

    // output the character the user entered
    cout << character << endl;

    // do something based on the character they gave (case-sensitive)
    switch (character) {
    case 'A':
        cout << "The first letter of the alphabet!" << endl;     
        break;
    case 'Z':
        cout << "The last letter of the alphabet!" << endl;
        break;
    default:
        cout << "I don't like that character!" << endl;
        break;
    }

    return 0;
}
Last edited on
Topic archived. No new replies allowed.