Sam
Sam

Reputation: 2347

C++ using command line args

I intend to enter a number into the command line such as saying "./a.out 3" where 3 would be the number I'm trying to retrieve. I'm wondering why in my example, the two numbers I'm trying to output aren't the same, and what is the most practical way of extracting info from the command line args? Thanks

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


    char* openSpace = argv[1];
    int temp = *openSpace;

    cout<<*openSpace<<" is the open spot!"<<endl;
    cout<<temp<<" is the open spot!"<<endl;

    return 0;
}

Upvotes: 1

Views: 242

Answers (3)

Pavel Zhuravlev
Pavel Zhuravlev

Reputation: 2791

You can not convert string to integer using an assignment like int temp = *openSpace;. You need to call a function for that, like atoi() from standard C library.

Upvotes: 1

Dietmar K&#252;hl
Dietmar K&#252;hl

Reputation: 153792

What do you mean, they are not the same? Surely they are! The first print the character '3' as character and the second prints it as an integer. That is you get ASCII value of the character '3'.

If you want to get it an integer value you can use something like atoi(), strtol(), boost::lexical_cast<int>(), etc.

Upvotes: 2

greg
greg

Reputation: 4953

argv[1] is a char* and you want an int. Unfortunately, you cannot just change the type of the variable. Instead, you must convert the char* to an int. Use the atoi() function for this.

int temp = atoi(argv[1]);

Upvotes: 8

Related Questions