Simple Question

I have created an error message if the user inputs the wrong selection number

1
2
3
4
if (choices < 1 || choices > 5)
{
cout << "\n Please Enter a number between 1-5 \n ";                            
}


How would i create a error message if the user inputs letters/words instead of a number.
First you need to have the user input a string. Then you need to see if the string is indeed an actual number. You will have to validate the number by processing the string character by character.

Alternatively, scanf only extracts certain characters based on the format string.
http://www.cplusplus.com/reference/cstdio/scanf/
Last edited on
Is there anyway you can give me an example of it. having trouble.
You're guaranteed valid input when you:

1.) Ensure that the fail state of std::cin has not been set.
2.) Ensure that the number is between one and five inclusive.

If I have the following code:

1
2
int i;
std::cin >> i;


and I enter something that's not an integer, std::cin will set the failbit flag, and it will be in a failure state. All kinds of crazy stuff can happen if the stream buffer associated with the std::cin istream object has extrenuous characters, or is in a failure state.

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
#include <iostream>
#include <string>
#include <limits>

void input_integer(int& i) {
	while(true) {
		std::cout << "Enter an integer between one and five (inclusive): ";
		if((std::cin >> i) && ((i>=1)&&(i<=5))) {//if std::cin can read into i without setting a fail flag, and i meets certain restrictions...
			break;//we can break out of the loop, effectively exiting the function, because i is guaranteed to be valid.
		}
		//if the previous conditions aren't satisfied...
		std::cin.clear();//we clear the fail flags of std::cin
		std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');//and discard any remaining characters in the stream buffer.
		//std::streamsize is a signed integral type used to represent the size of a buffer.
		//std::numeric_limits<std::streamsize>::max() returns the largest possible value of the streamsize type.
		//That value, n, is then the first parameter for std::cin.ignore(n, '\n'), which means n number of characters are discarded from the buffer, (in this case, the max number of characters the buffer could ever hold), or until the delimiter character ('\n') is extracted.
	}
}

int main(int argc, char* argv[]) {

	int i;
	input_integer(i);

	std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
	std::cin.get();
	return 0;
}
wow thanks! helps greatly!
Hi ace799,
I think @kevinkjt2000 offered a good solution for your problem(and likely more similar problem on user input validation), after we get the user input into a string, functions like sscanf()(in C) or stringstream STL(in C++) can be used to formalize and extract from the string.
Topic archived. No new replies allowed.