【问题标题】:c++ integer->std::string conversion. Simple function?c++ integer->std::string 转换。简单的功能?
【发布时间】:2008-11-07 22:52:08
【问题描述】:

问题:我有一个整数;这个整数需要转换为 stl::string 类型。

过去,我使用stringstream 进行转换,这有点麻烦。我知道 C 方法是做一个sprintf,但我更愿意做一个类型安全的 C++ 方法。

有没有更好的方法来做到这一点?

这是我过去使用的字符串流方法:

std::string intToString(int i)
{
    std::stringstream ss;
    std::string s;
    ss << i;
    s = ss.str();

    return s;
}

当然,这可以改写成这样:

template<class T>
std::string t_to_string(T i)
{
    std::stringstream ss;
    std::string s;
    ss << i;
    s = ss.str();

    return s;
}

但是,我认为这是一个相当“重量级”的实现。

Zan 注意到调用非常好,但是:

std::string s = t_to_string(my_integer);

无论如何,更好的方法是......很好。

相关:

Alternative to itoa() for converting integer to string C++?

【问题讨论】:

  • 在您的示例 t_to_string 中,我看不出为什么需要模板规范。模板函数可以根据其参数类型确定其模板类型。
  • @Zan:Durp。这就是我发布我没有编译的代码所得到的。
  • 下面的一些例子怎么样:codeproject.com/KB/recipes/Tokenizer.aspx 它们非常高效而且有点优雅。
  • @Beh:这个库比简单的 t_to_string() 重得多。它实际上看起来像一个非常好的库,但我不想仅仅为了做一个 t_to_string() 而导入整个东西。

标签: c++ integer stdstring


【解决方案1】:

现在在 c++11 中我们有

#include <string>
string s = std::to_string(123);

参考链接:http://en.cppreference.com/w/cpp/string/basic_string/to_string

【讨论】:

  • 非常漂亮。有指向描述该功能的标准页面的链接吗?
  • 我的编译器错误——“std::to_string: 对重载函数的模糊调用”
  • 我将把它改写为“终于,我们有......”。
【解决方案2】:

如前所述,我建议使用 boost lexical_cast。它不仅有相当不错的语法:

#include <boost/lexical_cast.hpp>
std::string s = boost::lexical_cast<std::string>(i);

它还提供了一些安全性:

try{
  std::string s = boost::lexical_cast<std::string>(i);
}catch(boost::bad_lexical_cast &){
 ...
}

【讨论】:

    【解决方案3】:

    不是真的,在标准中。一些实现有一个非标准的 itoa() 函数,你可以查看 Boost 的 lexical_cast,但是如果你坚持标准,它几乎可以在 stringstream 和 sprintf() 之间进行选择(如果你有的话,可以选择 snprintf())。

    【讨论】:

    猜你喜欢
    • 2019-05-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-05-20
    • 1970-01-01
    • 2019-12-06
    相关资源
    最近更新 更多