Quick OR operator question

Discussion in 'Mac Programming' started by larswik, Aug 12, 2010.

  1. larswik macrumors 68000

    Sep 8, 2006
    I am learning Obj C and I tried my own version of the 'OR' operator from the book I am learning from. I simply am having the NSLog display text if the person presses a key that is 'a' through 'n'. If they don't the 'while' loop returns them to the question. Everything works but if they press a key that is out of the range it runs the loop twice again before I can use the 'scanf' again to enter a new character. It's like the Loop is stuck in a loop. Here is the code.
    #import <Foundation/Foundation.h>
    int main (int argc, const char * argv[]) {
        NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];
    	char crit;
    	int testNum = 0;
    	while ( testNum == 0)
    	NSLog(@"What was the Crit:");
    	scanf("%c", &crit);
    		if ( crit < 'a' || crit > 'm')
    			NSLog(@"That is not a correct responce");
    	NSLog(@"You selected %c", crit);
        [pool drain];
        return 0;
    Any help would be great!
  2. lee1210 macrumors 68040


    Jan 10, 2005
    Dallas, TX
    Why not log the value of crit each time through? I'm guessing one of the extras is a newline, not sure about the third.

  3. iSee macrumors 68040


    Oct 25, 2004
    My first thought was the same as Lee's: it's the newline.

    One minor thing to add: It may be helpful to log the numeric value of the characters you scan rather than the character. E.g.:

    NSLog(@"char code: %d", (int)crit);

    Since we suspect the extra characters are whitespace, it could be hard to see them in the log if you just log them as characters.

    13 and 10 are newline and carriage return (I forget which is which).
  4. larswik thread starter macrumors 68000

    Sep 8, 2006
    Thanks. I'm still new to Programing and I am not sure what newline is. If is a character's ASCII number representation?

  5. chown33 macrumors 604

    Aug 9, 2009
    Sailing beyond the sunset
  6. larswik thread starter macrumors 68000

    Sep 8, 2006

Share This Page