PDA

View Full Version : Integer Arguments in Objective-C




hiddenpremise
Jan 15, 2009, 01:45 PM
How do I pass an integer value through the argv[] array?
ex

#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
pMac:/ premise$ ./myApp 7
in my terminal I get back some gigantic negative number that is not 7.



autorelease
Jan 15, 2009, 01:57 PM
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():

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

then

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.