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

larswik

macrumors 68000
Original poster
Sep 8, 2006
1,552
11
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.
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");
	
		else
			testNum++;
	}
	
	NSLog(@"You selected %c", crit);
	
	
    [pool drain];
    return 0;
}

Any help would be great!
 
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.

-Lee
 
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).
 
Thanks. I'm still new to Programing and I am not sure what newline is. If is a character's ASCII number representation?

-Lars
 
Register on MacRumors! This sidebar will go away, and you'll see fewer ads.