How to Prevent Chars and Special Chars in cin?

Good day guys, sorry im actually new in programming and my teacher asked us to make a Cashier program. So i used the do and while and also the switch case thing but my problem is everytime i put a char, speccial char or any unsual input with is not equal to a number. it outputs overflow of my default output. They call it a waterfall thing. So how do i fix it? sorry i wanted to put my program here but i dont know how and its too long.. anyway how to prevent chars or any kind of input which is not equal to a number that will say "invalid" and would not overflow.
check if the input char is in range of '0'-'9', if you are reading character by character
If you are expecting numbers like 899 as input using std::cin then

if you enter
eree, cin should give you zero
78e, cin should give 78
8989 should give you 8989
I think the op is reading in as an integer and is trying to avoid invalid input. There are actually a lot of ways to do this.

The two most common I think are
1) reading in as a string then parsing using std::getline
2) reading in with std::cin >> then if there are any error flags or left over characters in the buffer (excluding the newline left by cin>>) then clear the error flag and ignore everything left.


Here is what method two looks like:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19

#include <iostream>
#include <limits>

int main()
{
	int input;
	char c; //used for checking left over characters in buffer
	std::cout << "Please enter an integer: ";
	while( !(std::cin >> input) || //check if there are bad flags set
	( std::cin.get( c ) && c != '\n' ) ) //check if anything left in buffer
	{
    	        std::cin.clear(); //clear error flags 
    	        std::cin.ignore( std::numeric_limits<std::streamsize>::max() , '\n' ); //ignore anything left in buffer
    	        std::cerr << "Invalid input. << std::endl << Please try another integer: ";
	}
	std::cout << std::endl << "You entered: " << input << std::endl;
	return 0;
}
You entered: 5

http://ideone.com/gk44ir

clear -- http://www.cplusplus.com/reference/ios/ios/clear/
ignore -- http://www.cplusplus.com/reference/istream/istream/ignore/?kw=cin.ignore
*numeric_limts -- http://www.cplusplus.com/reference/limits/numeric_limits/?kw=numeric_limits

*can be replaced with a large number like 1024 , 500 , ect..


[edit]some how it didn't copy the spaces correctly
Last edited on
Topic archived. No new replies allowed.