任何人都知道如何将char数组转换为单个int?将char数组转换为单个int?
char hello[5];
hello = "12345";
int myNumber = convert_char_to_int(hello);
Printf("My number is: %d", myNumber);
任何人都知道如何将char数组转换为单个int?将char数组转换为单个int?
char hello[5];
hello = "12345";
int myNumber = convert_char_to_int(hello);
Printf("My number is: %d", myNumber);
长话短说,你必须使用atoi()
编辑:
如果你有兴趣做这个the right way:
char szNos[] = "12345";
char *pNext;
long output;
output = strtol (szNos, &pNext, 10); // input, ptr to next char in szNos (null here), base
ASCII字符串到整数的转换是由完成atoi()
功能。
这是你应该避免的。你如何检查错误? – 2011-05-23 08:37:15
使用sscanf
/* sscanf example */
#include <stdio.h>
int main()
{
char sentence []="Rudolph is 12 years old";
char str [20];
int i;
sscanf (sentence,"%s %*s %d",str,&i);
printf ("%s -> %d\n",str,i);
return 0;
}
不管怎样,都不是这样。例如,不要使用'“%s”',因为这会导致缓冲区溢出。总而言之,'stdtol'更简单,更安全。 – 2011-05-23 08:39:39
是不是'strtol'?为什么'strtol'比'atoi'好? – qed 2013-11-06 20:43:29
有一个字符串转换为一个int的多张的方式。
解决方案1:使用传统C功能
int main()
{
//char hello[5];
//hello = "12345"; --->This wont compile
char hello[] = "12345";
Printf("My number is: %d", atoi(hello));
return 0;
}
解决方案2:使用lexical_cast
(最适当&简单)
int x = boost::lexical_cast<int>("12345");
SOLU重刑3:使用C++ Streams
std::string hello("123");
std::stringstream str(hello);
int x;
str >> x;
if (!str)
{
// The conversion failed.
}
如果您正在使用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.
}
应当指出的是,“1234abc”是被传递到stoi()
前char[]
到std:string
implicitly converted。
我会在这里留给这个对没有依赖关系的实现感兴趣的人。
inline int
stringLength (char *String)
{
int Count = 0;
while (*String ++) ++ Count;
return Count;
}
inline int
stringToInt (char *String)
{
int Integer = 0;
int Length = stringLength(String);
for (int Caret = Length - 1, Digit = 1; Caret >= 0; -- Caret, Digit *= 10)
{
if (String[Caret] == '-') return Integer * -1;
Integer += (String[Caret] - '0') * Digit;
}
return Integer;
}
适用于负值,但不能处理混合在其间的非数字字符(应该很容易添加)。只有整数。
该代码是否按原样编译?它不应该。 – 2011-05-23 06:09:00
这不应该。 convert_char_to_int(hello)不是一个实际的函数。我问什么函数/方法我应该用来取代我的理论:“convert_char_to_int(hello)”? – IsThisTheEnd 2011-05-23 06:10:44
'hello'是一个不可修改的*左值*所以'hello =“12345”;'甚至不会编译。 – 2011-05-23 06:10:53