Humg12
Humg12

Reputation: 11

Using arg[v] as int? - Objective C

I'm trying to pass arguments into and integer variable at the start of my program in xcode using Objective C. So far most methods I've found have just given me a variety of error messages or crashed my VM.

int numcols, numrows;

int main(int argc, const char * argv[]) {
@autoreleasepool {

    if (argc != 3){
        NSLog(@"%2s", "Wrong number of arguments");
        exit(1);
    }

    //numrows = (int)(argv[1] - '0'); 
    //numcols = (int)(argv[2] - '0'); These lines cause a crash
    numrows = 3;
    numcols = 4;

I want numrows to take the first argument and numcols to take the second. I went into the settings in xcode to change the starting arguments to 3 and 4, but if I check them or print them they come out as random numbers.

Upvotes: 0

Views: 729

Answers (2)

Kundan
Kundan

Reputation: 3082

First of all your question is not clear, how much i understand i can say. As argc means argument count and argv means argument value. If you want to cast char to int. try this

[[NSString stringWithFormat:@"%s", argv[2]] intValue];

Upvotes: 1

CRD
CRD

Reputation: 53000

argv is an array of C strings. You cannot just cast a string to an integer, you need to parse the string to produce the integer value it represents.

You could write code to do this yourself, but fortunately there are library functions which handle this, for example see strtol which will parse a string and produce a long.

HTH

Upvotes: 2

Related Questions