Become a MacRumors Supporter for $50/year with no ads, ability to filter front page stories, and private forums.

renu

macrumors newbie
Original poster
Dec 27, 2011
1
0
I am trying to validate user input. Here's the code:

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
 
Last edited by a moderator:
%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?
 
When you're only reading single chars, consider using one of the single-character input functions: getc(), fgetc(), getchar().
 
Register on MacRumors! This sidebar will go away, and you'll see fewer ads.