c++用什么方法把字符串(char *)解析成int?健壮和清晰的错误处理是一个加分项(而不是返回零)。
当前回答
我认为这三个环节可以概括:
http://tinodidriksen.com/2010/02/07/cpp-convert-int-to-string-speed/ http://tinodidriksen.com/2010/02/16/cpp-convert-string-to-int-speed/ http://www.fastformat.org/performance.html
Stringstream和lexical_cast解决方案与lexical cast使用Stringstream大致相同。
词汇强制转换的一些专门化使用不同的方法,请参阅http://www.boost.org/doc/libs/release/boost/lexical_cast.hpp了解详细信息。整数和浮点数现在专门用于整型到字符串的转换。
可以根据自己的需要专门化lexical_cast,并使其快速运行。这将是让各方满意的最终解决方案,干净而简单。
前面提到的文章展示了转换整数<->字符串的不同方法之间的比较。以下方法是有意义的:旧c-way,精神。Karma, fastformat,简单的循环。
Lexical_cast在某些情况下是可以的,例如int到字符串的转换。
使用词法强制转换将字符串转换为int不是一个好主意,因为它比atoi慢10-40倍,这取决于所使用的平台/编译器。
karma似乎是将整数转换为字符串的最快的库。
ex.: generate(ptr_char, int_, integer_number);
上面文章中提到的基本简单循环是将字符串转换为int的最快方法,显然不是最安全的方法,strtol()似乎是更安全的解决方案
int naive_char_2_int(const char *p) {
int x = 0;
bool neg = false;
if (*p == '-') {
neg = true;
++p;
}
while (*p >= '0' && *p <= '9') {
x = (x*10) + (*p - '0');
++p;
}
if (neg) {
x = -x;
}
return x;
}
其他回答
您可以使用这个已定义的方法。
#define toInt(x) {atoi(x.c_str())};
如果要将String转换为Integer,只需执行以下操作。
int main()
{
string test = "46", test2 = "56";
int a = toInt(test);
int b = toInt(test2);
cout<<a+b<<endl;
}
输出是102。
我喜欢丹的回答,尤其是因为他避免了例外。对于嵌入式系统开发和其他低级别的系统开发,可能没有适当的Exception框架可用。
增加了一个有效字符串后的空白检查…这三行
while (isspace(*end)) {
end++;
}
还增加了对解析错误的检查。
if ((errno != 0) || (s == end)) {
return INCONVERTIBLE;
}
这是完整的功能..
#include <cstdlib>
#include <cerrno>
#include <climits>
#include <stdexcept>
enum STR2INT_ERROR { SUCCESS, OVERFLOW, UNDERFLOW, INCONVERTIBLE };
STR2INT_ERROR str2long (long &l, char const *s, int base = 0)
{
char *end = (char *)s;
errno = 0;
l = strtol(s, &end, base);
if ((errno == ERANGE) && (l == LONG_MAX)) {
return OVERFLOW;
}
if ((errno == ERANGE) && (l == LONG_MIN)) {
return UNDERFLOW;
}
if ((errno != 0) || (s == end)) {
return INCONVERTIBLE;
}
while (isspace((unsigned char)*end)) {
end++;
}
if (*s == '\0' || *end != '\0') {
return INCONVERTIBLE;
}
return SUCCESS;
}
在新的c++ 11中,有这样的函数:stoi, stol, stoll, stoul等等。
int myNr = std::stoi(myString);
它将在转换错误时抛出异常。
即使这些新函数仍然存在Dan指出的相同问题:它们会愉快地将字符串“11x”转换为整数“11”。
查看更多信息:http://en.cppreference.com/w/cpp/string/basic_string/stol
这是比atoi()更安全的C方式
const char* str = "123";
int i;
if(sscanf(str, "%d", &i) == EOF )
{
/* error */
}
c++与标准库stringstream:(感谢CMS)
int str2int (const string &str) {
stringstream ss(str);
int num;
if((ss >> num).fail())
{
//ERROR
}
return num;
}
使用boost library:(感谢jk)
#include <boost/lexical_cast.hpp>
#include <string>
try
{
std::string str = "123";
int number = boost::lexical_cast< int >( str );
}
catch( const boost::bad_lexical_cast & )
{
// Error
}
编辑:修正了stringstream版本,以便它处理错误。(感谢CMS和jk对原文的评论)
我喜欢Dan Moulding的回答,我将添加一点c++风格:
#include <cstdlib>
#include <cerrno>
#include <climits>
#include <stdexcept>
int to_int(const std::string &s, int base = 0)
{
char *end;
errno = 0;
long result = std::strtol(s.c_str(), &end, base);
if (errno == ERANGE || result > INT_MAX || result < INT_MIN)
throw std::out_of_range("toint: string is out of range");
if (s.length() == 0 || *end != '\0')
throw std::invalid_argument("toint: invalid string");
return result;
}
通过隐式转换,它对std::string和const char*都有效。它也适用于基转换,例如,所有to_int("0x7b")和to_int("0173")和to_int("01111011", 2)和to_int("0000007B", 16)和to_int("11120", 3)和to_int("3L", 34);返回123。
与std::stoi不同,它可以在pre- c++ 11中工作。也不像std::stoi, boost::lexical_cast和stringstream,它会抛出奇怪的字符串异常,比如“123hohoho”。
注意:此函数允许前导空格,但不允许尾随空格,即to_int("123 ")返回123,而to_int("123 ")抛出异常。确保这对于您的用例是可接受的,或者调整代码。
这样的功能可能是STL的一部分…
推荐文章
- 为什么这个结合赋值和相等检查的if语句返回true?
- cplusplus.com给出的错误、误解或坏建议是什么?
- 找出质数最快的算法是什么?
- 在c#中解析字符串为日期时间
- c++枚举类可以有方法吗?
- 格式化IO函数(*printf / *scanf)中的转换说明符%i和%d之间的区别是什么?
- 将析构函数设为私有有什么用?
- main()中的Return语句vs exit()
- 为什么c#不提供c++风格的'friend'关键字?
- 在函数的签名中添加关键字
- 我如何在Visual Studio中预处理后看到C/ c++源文件?
- 为什么在标准容器中使用std::auto_ptr<>是错误的?
- 用比较double和0
- 保护可执行文件不受逆向工程的影响?
- 在c++中字符串前面的“L”是什么意思?