How do I get an integer user input from command line?

Discussion in 'Mac Programming' started by ataylor2009, Mar 18, 2009.

  1. ataylor2009 macrumors member

    Jan 27, 2009
    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.
  2. mdeh macrumors 6502

    Jan 3, 2009

    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.

    #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;
  3. ataylor2009 thread starter macrumors member

    Jan 27, 2009
    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.
  4. autorelease macrumors regular

    Oct 13, 2008
    Achewood, CA
    Use fgets() to read the input as a string, then convert the string to an integer with strtol().
  5. jw2002 macrumors 6502

    Feb 23, 2008
    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.

Share This Page