c++用什么方法把字符串(char *)解析成int?健壮和清晰的错误处理是一个加分项(而不是返回零)。


当前回答

我喜欢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的一部分…

其他回答

这是比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对原文的评论)

我认为这三个环节可以概括:

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;
}

你可以使用c++标准库中的a stringstream:

stringstream ss(str);
int x;
ss >> x;

if(ss) { // <-- error handling
  // use x
} else {
  // not a number
}

流状态将被设置为失败 当遇到非数字时 正在读取一个整数。

有关c++中错误处理和流的陷阱,请参阅流陷阱。

您可以使用这个已定义的方法。

#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;
}