How To Deal With User Pressing <Enter> When Prompted For An in (cin >> int)

I'm working on a menu based program. The actions performed are based on an integer that the user inputs via cin. In order to validate the integer I check cin.fail() and I also check to make sure that it is within range. How do I deal with the user simply pressing <Enter> when prompted to make a selection? I want to be able to display the appropriate error message and prompt them to try again.

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
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
for(;;)
{
        int num;
	cout << "Main Menu" << endl;
	cout << "(1) Option 1" << endl;
	cout << "(2) Option 2" << endl;
	cout << "(3) Option 3" << endl;
	cout << "(4) Option 4" << endl;
	cout << "(5) Quit" << endl;
	cout << "Please enter a number: ";
	cin >> num;

	if(cin.fail())
	{
		cout << "Input failed. Try again." << endl;
		cin.clear();
		cin.ignore(1000, '\n'); 
		continue;
	}

	else if(num < 1 || num > 5)
	{
		cout << "Selection must be between 1 and 5." << endl;
		cin.ignore(1000, '\n');
		continue;
		
	}
	else if(num == 1)
	{
		optionOne();
		cin.ignore(1000, '\n');
		continue
	}
	else if(num == 2)
	{
		optionTwo();
		cin.ignore(1000, '\n');
		continue
	}
	else if(num == 3)
	{
		optionThree();
		cin.ignore(1000, '\n');
		continue
	}
	else if(num == 4)
	{
		optionFour();
		cin.ignore(1000, '\n');
		continue
	}
	else
	{
		cin.ignore(1000, '\n');
		break
	}
}


When the user presses <Enter>, no error message is printed and the program hangs until another value is entered. What do I do to fix this?
You'll have to read input differently.
cin>>int skips leading whitespace, including newlines.
I think you will have to use low level functions like get and getline.
Last edited on
I would recommend using getline(), then taking the string and using a stringstream to convert it to an integer. I wouldn't consider that any lower level than the extraction operators, though.
Copy and paste this into your code..you will need to add the string, and sstream header to the file.

1
2
3
4
5
6
7
8
9
10
11
        string myString;
        int num;
	cout << "Main Menu" << endl;
	cout << "(1) Option 1" << endl;
	cout << "(2) Option 2" << endl;
	cout << "(3) Option 3" << endl;
	cout << "(4) Option 4" << endl;
	cout << "(5) Quit" << endl;
	cout << "Please enter a number: ";
	getline (cin,myString);
	stringstream(myString) >> num;
Example in action:

Press ENTER twice to finish
http://www.cplusplus.com/forum/beginner/2409/#msg9254
You could use a Map of functionpointers, this would reduce the amount of logical operators, if, else if, else ....

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
//1 The type
typedef void(YourInputActionClass::*FuncPointer)(void); 
/** Declare a type which is a function pointer 
* to the class which handles the input actions. 
* The "void" return and parameter can be changed to 
* anything you like. However all functions in the map should 
* have the same return value and parameters. 
**/

//2 The map looks like this
std::map<std::string, Func> map_of_function_pointers; 
/** the string in this chase is the identifier for your function, 
* you can change this to and int or any other primitive type. 
* It depends on the user input
**/

//3 Initialize 
map_of_fuction_pointers["input_indentifier"] = &YourInputActionClass::name_of_function;

//4 How to use:
*(map_of_function_pointers[choice])( void ) 
/** Second paratense includes the function parameters which you delclared in (1)
* This is would be equivalent to running    name_of_function(void)
**/


Might be difficult to understand at first but is very useful to know =)
Last edited on
maybe this is better
1
2
3
4
5
6
7
8
9
10
11
      
        char num;
	cout << "Main Menu" << endl;
	cout << "(1) Option 1" << endl;
	cout << "(2) Option 2" << endl;
	cout << "(3) Option 3" << endl;
	cout << "(4) Option 4" << endl;
	cout << "(5) Quit" << endl;
	cout << "Please enter a number: ";
	num=getch();


instead of int num, u use char num
u wont need to press <ENTER> after a input and u wont even see the input

of course u will need to include conio.h, and insted of comparing intigers u will compare characters
Last edited on
No, conio.h is non-standard so I would recommend against using it.
im not sure what diference it makes if its standard or not, so i would appreciate i u could explain it to me.
and using getch(), the input would not be displayed on the screen, so i think thats a plus
How is not doing what the user expects a plus?
(Hint: If you give a prompt, the user expects to see his response.)

By using standard libraries you reduce the liklihood of compile and/or execute failure.
the response would be the screen changing into the menu he selected by the input, or an error message if he did wrong input, specificly in jokermans example.

and thx for explaining why use standard over non-standard
Believe it or not, I have a significant amount of experience in UI design, and simple console menu systems really aren't over my head. The program's response != the user's response.

When people see a prompt like
Please enter a number: _
they really do kind of expect to see what they are typing appear on the screen. This is consistent with the behavior of the rest of the program, and with all other programs in its class. (That colon and blinking cursor are huge cues here.)

A program behaves properly when it behaves the way the user expects it to behave.
aha, yes that makes sense.

so in order to make getch() consistent to what the user expects, we should have something like this on the screen:

RANDOM MENU

1.  Get some value
2.  Input some value
3.  Show statistics

Enter your choice.      //( or something like that)


without the _ prompt.

This way the user wont expect to see his input, but instead to see the program response when he presses the key, or am i getting it all wrong again?

truly, every day you learn something new ^^
Yes, you are getting closer. When you say "Enter" you are telling the user that he is expected to type things, which he will see, and then press ENTER.

Better yet is something like:

┌─────────────────────┐
│ RANDOM MENU         │
├─────────────────────┤
│ 1. Get Some Value   │
│ 2. Input Some Value │
│ 3. Show Statistics  │
│ 9. Exit             │
└─────────────────────┘

Notice the lack of a cursor or a textual prompt. This strongly indicates that the user only need type the number indicated and that the computer will instantly respond to it.

Hope this helps.
|
yes thats helps thx
Topic archived. No new replies allowed.