c++ Why can't I use static_cast to convert char* to int?

三世轮回 提交于 2019-12-13 11:29:24

问题


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.


回答1:


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

int number = atoi(argv[1])



回答2:


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.




回答3:


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()




回答4:


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




回答5:


What you are looking for is:

#include <cstdlib>
// ...
number = atoi(argv[1]);



回答6:


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



来源:https://stackoverflow.com/questions/17008409/c-why-cant-i-use-static-cast-to-convert-char-to-int

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!