C++ Programming Assignment: Char Issue

I'm working on an assignment for one of my programming classes and ran into the following issue. As you can see the program outputs a menu and the user enters their choice (denoted as the char variable option). The issue is if the user enters a value such as 23 as an input the program takes the last entered char, in this case 3. This programming assignment specifically asked for this variable to be a char. Is there anyway to have the program recognize that the user entered two characters and not one?

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
  char Menu ()
  {
	bool flag = true;
	char option;
	while ( flag )
	{
		cout << setw(4) << setfill(' ') << ' '
		     << "1 - Change office from occupied to empty" << endl;
		
		cout << setw(4) << setfill(' ') << ' '
	             << "2 - Modify office occupant type" << endl;
		
		cout << setw(4) << setfill(' ') << ' '
		     << "3 - Change office from empty to occupied" << endl;
		
		cout << setw(4) << setfill(' ') << ' '
		     << "D - Done making modifications" << endl;
		
		cout << "Enter option: ";
		cin >> option;
		option = toupper (option);
		
		if (option == '1' || option == '2' || option == '3' || option == 'D')
		{
			return option;
		}
		else if( option != '1' || option != '2' || option != '3' || option != 'D' )
		{
			cout << "ERROR: Invalid option entered. Try again." << endl << endl;
		}
	}
}
you could use string instead of char.
If you must use char, you can try something like this:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
#include <iostream>

using namespace std;


int main()
{
	char c[2]; // size of char array doesn't actually matter as long as it's >=1

	cin.get(c, 3); // reads 3-1=2 char from stream

	if(cin.gcount() >= 2) 
		cout << "ERROR: TOO MANY CHAR" << endl;

	cin.clear(); //clears cin error flags

	cin.ignore(1000, '\n'); //clears 1000 char from stream buffer

	return 0;

}


The gcount() is a function that counts how many times you use a cin function to get an input value. In this case gcount() counts the number of times we received input from get() cin function.
Last edited on
Thank you both SamuelAdams and DyslexicChciken. I'll mark this one as solved. Thank you both again for your help.
Topic archived. No new replies allowed.