-4
number = static_cast<int>(argv[1]);

Error: Using static_cast to convert from char* to int not allowed.

I've tried finding out why on google and I just can't seem to find it. Also, I don't want to get the ascii value, because argv[1] is a number.

e.g. ./prog 15

cout << number; //want it to print 15.

user2369405
  • 217
  • 1
  • 4
  • 10

6 Answers6

6

You just try to convert char* to int. You code should be:

int number = atoi(argv[1])
zsxwing
  • 20,270
  • 4
  • 37
  • 59
4

You can use this: std::stoi function. It's totally C++, not like one borrowed from c libraries.. atoi.

 number=std::stoi( argv[1])
 cout<<number;

Or if your goal is to just print then:

cout<<argv[1]; suffice.

Why your method doesn't work?:

Because you were trying to cast argv[1], which is a pointer of type char * to int, which is illegal. Doing that will not right away convert into an integer. You have to iterate the string letter by letter in order convert it to an integer number. That's what really done in library functions like, std::stoi or atoi.

pinkpanther
  • 4,770
  • 2
  • 38
  • 62
2

You cant convert char * to int. You are trying to convert "string" to number, which is not possible with static_cast.

For converting string to number, you must use function like atoi()

Martin Perry
  • 9,232
  • 8
  • 46
  • 114
1

It would be an error do so because arguments are passed as strings. So what yo get is a pointer to char. To convert it to an int you have to use conversion functions like for instance atoi

Philip Stuyck
  • 7,344
  • 3
  • 28
  • 39
1

What you are looking for is:

#include <cstdlib>
// ...
number = atoi(argv[1]);
user1055604
  • 1,624
  • 11
  • 28
0

Because argv[1] is a char *, not a char. Perhaps you meant to access one of its characters, like argv[1][0]?