任何人都知道如何将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)
如果您正在使用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)