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

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

  1. 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. macrumors 68000


    Feb 26, 2008
  3. 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;
  4. 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.
  5. 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().
  6. 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