Trying to check if input is an integer & within range

Hello

I am trying to test if the cin input matches my criteria.

I want the program to check if the input is an integer AND if it's within range (1-4). It is for a basic menu system for a minesweeper game...

Here's what I have:

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
start:										//<<<<<<<<<<<<<<<START>>>>>>>>>>>>>>>>>>
    
	
	cout << "Welcome to Minesweeper:" <<endl<<endl;
	cout << "1. New Game." <<endl;
	cout << "2. Replay previous Game." <<endl;									
	cout << "3. Help." <<endl;
	cout << "4. QUIT Program" <<endl<<endl;
	cout << "Please select an option: ";
	cin >> select;
	{
	if(!cin)		//Checking if input is an integer
	{
		system("cls");
		cout << "INPUT FAIL!"<<endl<<endl;
		cout << "Please only use numbers when making selection.";
                system("pause > nul");
		goto start;
	}
	else if ((select < 1) || (select > 4))		//Checking if input is within selection range (1 - 4)
	{
		system("cls");
		cout << "Please select 1 - 4 ONLY";
		system("pause > nul");
		select=0;
		goto start;


When debugging the program, the program loops around the first IF statement over and over. Do I need to clear the int 'select' before going back to start?
Last edited on
You need to clear the error condition for non-integer input. Also clear the invalid characters from the input buffer.
12
13
14
15
16
17
if (!cin)
{
    cin.clear();              // clear the error flags
    cin.ignore(1000,'\n');    // empty the input buffer
    // etc.....
}


The use of system("pause") should not be necessary, the program will pause as it awaits user input in any case.
Last edited on
Thank you!

Now, I need to use this function multiple times in my code. How would I include this in a header file I already have that contains other useful functions that I have been calling to in my code?

Just putting this doesn't work when compiling:

1
2
3
4
5
6
7
8
9

//In functions.h

int clearbuffer();
{
    cin.clear();             
    cin.ignore(1000,'\n');   
    return 0;
}


I get "cin - undeclared identifier" error when compiling main.cpp

What to I need to do to it to get it to work?

Thanks.


Last edited on
Well you need to either specify somewhere in the scope of cin that you're using std namespace, or attach std:: in front of cin.
Well you need to either specify somewhere in the scope of cin that you're using std namespace, or attach std:: in front of cin.


Bingo! Thank you both for your help, much appreciated.
Topic archived. No new replies allowed.