如何将C ++字符串转换为int?

时间:2008-10-14 05:35:30

标签: c++ parsing int stdstring

  

可能重复:
  How to parse a string to an int in C++?

如何将C ++字符串转换为int?

假设您希望字符串中包含实际数字(例如“1”,“345”,“38944”)。

另外,让我们假设你没有提升,你真的想用C ++的方式来做,而不是狡猾的旧C方式。

8 个答案:

答案 0 :(得分:74)

#include <sstream>

// st is input string
int result;
stringstream(st) >> result;

答案 1 :(得分:33)

使用C ++流。

std::string       plop("123");
std::stringstream str(plop);
int x;

str >> x;

/* Lets not forget to error checking */
if (!str)
{
     // The conversion failed.
     // Need to do something here.
     // Maybe throw an exception
}

PS。这个基本原则是加速库lexical_cast<>的工作原理。

我最喜欢的方法是提升lexical_cast<>

#include <boost/lexical_cast.hpp>

int x = boost::lexical_cast<int>("123");

它提供了一种在字符串和数字格式之间进行转换的方法。在它下面使用一个字符串流,所以任何可以编组成流然后从流中取消编组的东西(看看&gt;&gt;和&lt;&lt;运算符)。

答案 2 :(得分:4)

我之前在C ++代码中使用过类似的内容:

#include <sstream>
int main()
{
    char* str = "1234";
    std::stringstream s_str( str );
    int i;
    s_str >> i;
}

答案 3 :(得分:4)

C ++ FAQ Lite

[39.2]如何将std :: string转换为数字?

https://isocpp.org/wiki/faq/misc-technical-issues#convert-string-to-num

答案 4 :(得分:2)

让我加上对boost :: lexical_cast

的投票
#include <boost/lexical_cast.hpp>

int val = boost::lexical_cast<int>(strval) ;

它会在错误时抛出bad_lexical_cast

答案 5 :(得分:0)

使用atoi

答案 6 :(得分:0)

也许我误解了这个问题,为什么想要使用 atoi ?我认为重新发明轮子毫无意义。

我在这里错过了这一点吗?

答案 7 :(得分:-6)

在“stdapi.h”中

StrToInt

此函数会告诉您结果以及转换中参与的字符数。

相关问题