1

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;
}

3 Answers 3

8

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]);
Sign up to request clarification or add additional context in comments.

1 Comment

Take a look at boost's lexical_cast also.
2

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.

Comments

1

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.