Objective C - Validating user input

Discussion in 'Mac Programming' started by renu, Dec 27, 2011.

  1. renu, Dec 27, 2011
    Last edited by a moderator: Dec 28, 2011

    macrumors newbie

    Joined:
    Dec 27, 2011
    #1
    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
     
  2. macrumors 65816

    jiminaus

    Joined:
    Dec 16, 2010
    Location:
    Sydney
    #2
    %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?
     
  3. macrumors 603

    Joined:
    Aug 9, 2009
    #3
    When you're only reading single chars, consider using one of the single-character input functions: getc(), fgetc(), getchar().
     
  4. macrumors 68000

    Joined:
    Mar 29, 2009
    Location:
    USA
    #4
    Right, scanf() sucks for this kind of stuff.
     

Share This Page