1

Simple question I'm having an annoying time with:

My main is set up as such:

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

   int i = (int) argv[1];
   cout << "Inputted value: " << i << endl;
   return 0;
}

If I compile and execute with g++ main.cc -o main and main 5 I get a garbage result back on cout. How do I fix this casting issue?

  • 7
    Command line arguments are received as strings (even if they're strings of digits). To convert the string to a number, you'd use something like `std::stoi`. – Jerry Coffin Nov 16 '14 at 22:10
  • This is why C-style casts are dangerous. – aschepler Nov 16 '14 at 22:10
  • 1
    @remyabel: A cast from `char*` to `int` is perfectly legal, though the result is at best implementation-defined. And the "loses precision" warning probably depends on relative sizes of `char*` and `int`; on many systems, they're both 32 bits. (Though "precision" doesn't really apply to pointer values.) – Keith Thompson Nov 16 '14 at 23:23
  • 1
    Please update your question to indicate what you're trying to do. Are you trying to get the `int` value `42` if the command line argument is the string `"42"`? – Keith Thompson Nov 16 '14 at 23:24

1 Answers1

2

You are trying to cast a string to int, which will not work. You need to use one of the string to integer conversion functions.

int atoi (const char * str);

MSDN

Bart
  • 547
  • 3
  • 16
  • No, he's trying to cast a *pointer* to `int`. – Keith Thompson Nov 16 '14 at 23:23
  • zZShort_CircuitZz's intent was to cast a string to integer, which is not what actually happens. – Bart Nov 17 '14 at 10:44
  • `atoi` is a terrible choice. Please read http://stackoverflow.com/a/6154614/103167 – Ben Voigt Feb 20 '15 at 17:11
  • I am fully aware that there are safer functions than atoi. I was merely pointing @zZShort_CircuitZz to the existence of conversion functions. If atoi is unsafe depends on the situation it is used in. – Bart Feb 23 '15 at 08:16