将char数组转换为单个int?

IsT*_*End 22 c++ int char

任何人都知道如何将char数组转换为单个int?

char hello[5];
hello = "12345";

int myNumber = convert_char_to_int(hello);
Printf("My number is: %d", myNumber);
Run Code Online (Sandbox Code Playgroud)

Alo*_*ave 36

有多种方法可以将字符串转换为int.

解决方案1:使用Legacy C功能

int main()
{
    //char hello[5];     
    //hello = "12345";   --->This wont compile

    char hello[] = "12345";

    Printf("My number is: %d", atoi(hello)); 

    return 0;
}
Run Code Online (Sandbox Code Playgroud)

解决方案2:使用lexical_cast(最合适和最简单)

int x = boost::lexical_cast<int>("12345"); 
Run Code Online (Sandbox Code Playgroud)

解决方案3:使用 C++ Streams

std::string hello("123"); 
std::stringstream str(hello); 
int x;  
str >> x;  
if (!str) 
{      
   // The conversion failed.      
} 
Run Code Online (Sandbox Code Playgroud)

  • @Als:使用`boost :: lexical_cast`.`atoi`不安全! (3认同)
  • ...而不是`atoi``strtol`应该使用,在这种情况下更合适 - 不需要使用boost只是为了这个简单的操作... (3认同)

Ric*_*ith 6

如果您正在使用C++11,您应该使用stoi它,因为它可以区分错误和解析"0".

try {
    int number = std::stoi("1234abc");
} catch (std::exception const &e) {
    // This could not be parsed into a number so an exception is thrown.
    // atoi() would return 0, which is less helpful if it could be a valid value.
}
Run Code Online (Sandbox Code Playgroud)

应当指出的是,"1234abc"被隐式转换char[]一个std:string被传递到前stoi().


Ren*_*eno -2

长话短说,你必须使用atoi()

编者:

如果您有兴趣以正确的方式执行此操作:

char szNos[] = "12345";
char *pNext;
long output;
output = strtol (szNos, &pNext, 10); // input, ptr to next char in szNos (null here), base 
Run Code Online (Sandbox Code Playgroud)

  • 不,你不这样做,也不应该在任何新代码中使用 - 请改用“strtol”! (2认同)
  • @Reno 在**不**的情况下,应该鼓励初学者养成坏习惯。 (2认同)