View Single Post
  #5 (permalink)  
Old 05-03-2008, 10:05 AM
mholt mholt is offline
Newbie
 
Join Date: Jan 2008
Posts: 27
Rep Power: 4
mholt is on a distinguished road
Default Re: Input Validation

Maybe.... there is one way that I know of that works pretty well... but if they make a mistake, Backspace won't help them:

Try the C function getch():

Code:
// Be sure to include conio.h
// This function returns a string
// of only numbers, validated
// as typed.

string EnterOnlyNumbers() {
	string numString = "";
	char ch = getch();
	while (ch != '\r') { // \r is the enter key
		if (ch >= '0' && ch <= '9') {
			cout << ch;
			numString += ch;
		}
		ch = getch();
	}
	return numString;
}
If you modify it a little bit, you can use this code for password input, so the password will not be displayed on the screen. (Print out "*" instead of ch.)

However, my compiler gives me warnings on the getch() function, probably because it is indeed depreciated. If you want the best code, getline() as a string then validate it.
Reply With Quote

Sponsored Links