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

ataylor2009

macrumors member
Original poster
Jan 27, 2009
78
0
I've looked in the NSString class reference, but didn't find anything that looked correct. scanf("%i", &varName) isn't working. What am I doing wrong?

int varName;
NSLog (@"Enter a number: ");
scanf("%i", &varName);
NSLog (@"You entered %i.", varName);

When I run this, I get the prompt "Enter a number:" followed by a blinking cursor. However, when I enter a number (or a letter or a space or just press return) nothing happens. Cursor moves to a new line and waits for input. I have to stop the process from the Xcode console window.

Thanks in advance.
 

mdeh

macrumors 6502
Jan 3, 2009
345
2
I've looked in the NSString class reference, but didn't find anything that looked correct. scanf("%i", &varName) isn't working. What am I doing wrong?

int varName;
NSLog (@"Enter a number: ");
scanf("%i", &varName);
NSLog (@"You entered %i.", varName);

When I run this, I get the prompt "Enter a number:" followed by a blinking cursor. However, when I enter a number (or a letter or a space or just press return) nothing happens. Cursor moves to a new line and waits for input. I have to stop the process from the Xcode console window.

Thanks in advance.


I just ran it and it works just fine for an integer, which is what you are asking for in scanf. ( the term "varName" for int is a little confusing). If you enter anything other than an integer, you are betraying what you asked for.

Code:
#import <Foundation/Foundation.h>

int main (int argc, const char * argv[]) {
    NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];

    int integerVal;
	NSLog (@"Enter a number: ");
	scanf("%i", &integerVal);
	NSLog (@"You entered %i.", integerVal);
    [pool drain];
    return 0;
}
 

ataylor2009

macrumors member
Original poster
Jan 27, 2009
78
0
Figured it out (well, I figured ONE thing out, anyway)...hitting the "Enter" key on the numeric keypad doesn't work; hitting "Return" on the main keyboard does.

I think that confuses me more than my original problem...anybody have an explanation (and a fix? I certainly want my users to be able to press whichever enter key floats their boat) for that one?

Thanks for your help, BTW.
 

jw2002

macrumors 6502
Feb 23, 2008
392
59
Use fgets() to read the input as a string, then convert the string to an integer with strtol().

Agree. I have never had good luck with scanf(). It doesn't have the robust error detection capabilities that strtol() has, so if the user enters "blort" or "6.4", then you are at the mercy of scanf() and whatever junk it decides to dump into your integer pointer.
 
Register on MacRumors! This sidebar will go away, and you'll see fewer ads.