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

hiddenpremise

macrumors regular
Original poster
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.
 
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.
 
Register on MacRumors! This sidebar will go away, and you'll see fewer ads.