glennib
glennib

Reputation: 63

Cast element of character array to integer, and print using cout

I have something in my opinion unexpected happening here.

int main(int argc, char* argv[]) {
    cout << "argv[1] : " << argv[1] << endl;
    cout << "(int)argv[1] : " << (int)argv[1] << endl;
}

When I call this:

$ ./a.out 1

The output is:

argv[1] : 1
(int)argv[1] : -1074470344

I would expect

argv[1] : 1
(int)argv[1] : 49

Since the ASCII code for '1' is 49.

What is happening here?

Upvotes: 2

Views: 137

Answers (3)

songyuanyao
songyuanyao

Reputation: 172864

argv[1] is not a char, it's a char *.

(int)argv[1][0] may be what you want, if you guarantee the argument will be only one character.

cout << "(int)argv[1][0] : " << (int)argv[1][0] << endl;

and you will get:

argv[1] : 1
(int)argv[1][0] : 49

NOTICE

If your argument is a string like "11", you will get a strange result such as:

argv[1] : 11
(int)argv[1][0] : 49

Upvotes: 2

L&#225;szl&#243; Papp
L&#225;szl&#243; Papp

Reputation: 53173

cout << "(int)argv[1] : " << (int)argv[1] << endl;

You are trying to cast argv[1] which is a char pointer, i.e. "C string". It could also contain "11", not just '1'.

You would need to "cast" the first letter, but I think it is not a good idea either way.

Furthermore, you have not checked against the argc whether you actually supplied the argument on the command line. That is another mistake unless you can make sure somehow it is never "misused".

Yet another mistake is not returning an integer, e.g. zero, at the end of the function since it should, otherwise you will get a warning from your compiler.

You could write this:

#include <iostream>

using namespace std;

int main(int argc, char** argv)
{
    if (argc == 1)
        return 1;
    cout << "argv[1] : " << argv[1] << endl;
    cout << "(int)argv[1][0] : " << (int)argv[1][0] << endl;
                         ^^^                    ^^^
    return 0;
}

That being said, you probably want to use static_cast for this in a C++ program rather than low-level C-type cast.

Upvotes: 0

Yu Hao
Yu Hao

Reputation: 122373

Remember that the type of argv is char* argv[], so argv[1] is not a single char, but a C-style string.

To print the first character, use argv[1][0].

std::cout << "(int)argv[1][0] : " << (int)argv[1][0] << std::endl;

Upvotes: 2

Related Questions