Integer Arguments in Objective-C

Discussion in 'Mac Programming' started by hiddenpremise, Jan 15, 2009.

  1. hiddenpremise macrumors regular

    hiddenpremise

    Joined:
    Jul 25, 2008
    Location:
    Somewhere between my imagination and reality
    #1
    How do I pass an integer value through the argv[] array?
    ex
    Code:
    #include <Foundation/Foundation.h>
    int main (int argc, const char * argv[])
    {
     NSLog(@"The int value you passed was: %d", argv[1]);
     return (0);
    }
    
    If I were to then run this
    Code:
    pMac:/ premise$ ./myApp 7
    in my terminal I get back some gigantic negative number that is not 7.
     
  2. autorelease macrumors regular

    Joined:
    Oct 13, 2008
    Location:
    Achewood, CA
    #2
    All elements in the argv array are C strings. You're trying to print a char* formatted as an integer, which is why you see a garbage number.

    If you want to convert a string to an int, use strtol():

    Code:
    int firstArg = (int)strtol(argv[1], NULL, 10);
    then

    Code:
    NSLog(@"The int value you passed was: %d", firstArg);
    will work. See the manpage for more details. There is a simpler function for converting a string to an integer called atoi(), but it's outdated and not thread-safe.
     

Share This Page