【问题标题】:How do you convert a C++ string to an int? [duplicate]如何将 C++ 字符串转换为 int? [复制]
【发布时间】:2010-09-17 00:54:27
【问题描述】:

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

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

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

另外,假设你没有 boost,你真的想用 C++ 方式来做,而不是笨拙的旧 C 方式。

【问题讨论】:

标签: c++ parsing int stdstring


【解决方案1】:

使用 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。这个基本原则就是 boost 库 lexical_cast<> 的工作原理。

我最喜欢的方法是 boost lexical_cast<>

#include <boost/lexical_cast.hpp>

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

它提供了一种在字符串和数字格式之间相互转换的方法。在它下面使用字符串流,因此可以将任何可以编组到流中然后从流中解组的内容(查看 >> 和

【讨论】:

  • 不应该是“if (!x)...”吗?
  • 没有。如果流操作符从 str 中提取数字失败,它会设置坏位。在布尔上下文(如上)中使用 this 将通过返回可转换为 bool 的对象来测试流是否正常。如果我测试了“x”,那么如果“x”中的值为 0,它将失败。如果流无法提取任何内容,则“x”的值是未定义的。
  • 它设置 fail 位,而不是 bad 位。操作员!是 fail() 的同义词。
【解决方案2】:

使用atoi

【讨论】:

  • 不是特别 C++ 吗?甚至 std::atoi 也不是真正的 C++...
  • atoi() 还具有其他魔法……比如忽略前导空格、忽略尾随非空格,以及假设“0”也是有效的错误条件。请仅在您真的不关心有效性时使用 atoi() 。否则,C 中的 strtod() 和 C++ 中的 std::istringstream。
【解决方案3】:
#include <sstream>

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

【讨论】:

  • 出现错误怎么办?假设字符串中没有数字(“hello!”而不是“5”)。
  • 然后检查错误: (stringstream(st) >> result) ? cout
【解决方案4】:

在“stdapi.h”中

StrToInt

这个函数告诉你结果,有多少字符参与了转换。

【讨论】:

  • 嗯?谷歌搜索这个“stdapi.h”并没有出现任何结果。你的意思是“shlwapi.h”(它是 Windows 特定的,是 shell DLL 的一部分,相当于旧的 C 方法)?
【解决方案5】:

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

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

【讨论】:

  • 好的。有人已经提出了这个建议,所以我提高了他们的水平。
【解决方案6】:

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

我只是错过了这里的重点吗?

【讨论】:

  • atoi() 的手册页说,“ atoi() 函数被 strtol() 包含,但由于它在现有代码中广泛使用而被保留。如果不知道该数字在范围,应该使用 strtol(),因为 atoi() 不需要执行任何错误检查。"
  • 我虽然 atoi() 是非标准的,因此并非在任何地方都可用。不过可能是错的。
  • 这是一个很好的观点,克鲁潘。我承认我没有想到这一点。
  • atoi() 也会忽略前导空格和尾随废话,因此它可能会在其他更严格的解析器失败的情况下成功。根据您的 POV,这可能是优势也可能是障碍。
【解决方案7】:

C++ 常见问题精简版

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

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

【讨论】:

  • 最好的方法,恕我直言,尤其是使用可配置的 fail_on_leftover
  • 什么是“fail_on_leftover”?
【解决方案8】:

让我投票支持 boost::lexical_cast

#include <boost/lexical_cast.hpp>

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

出错时抛出bad_lexical_cast

【讨论】:

    猜你喜欢
    • 2013-11-12
    • 2012-07-04
    • 2011-06-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-01-30
    • 2017-02-18
    • 2020-08-27
    相关资源
    最近更新 更多