PDA

View Full Version : Objective C - Validating user input




renu
Dec 28, 2011, 12:12 AM
I am trying to validate user input. Here's the code:

do{
NSLog(@"Please select from the following options: D/ W/ T/ Q");
res = scanf("%c", &s1);

if(res ==0) {
NSLog(@"Invalid entry.");
}
}while (res ==0);

I want to improve the above code such that it will not allow the user to input anything (such as a number, a string, or any negative number) but only one single character (to be specific, only one of the option given in the prompt).

The current code doesn't do that.

Many thanks,

Renu



jiminaus
Dec 28, 2011, 12:56 AM
%c in scanf will cause only a single character to be read, but it will read any character. So your job is to check which character is being read. If the character read is not 'D' and not 'W' and not 'T' and not 'Q' (or perhaps the lowercase equivalents as well), you want to print an error message and then loop. Can you translate that into code?

chown33
Dec 28, 2011, 09:58 AM
When you're only reading single chars, consider using one of the single-character input functions: getc(), fgetc(), getchar().

robvas
Dec 28, 2011, 03:28 PM
When you're only reading single chars, consider using one of the single-character input functions: getc(), fgetc(), getchar().

Right, scanf() sucks for this kind of stuff.