【问题标题】:Convert a Long in a String C++? [duplicate]在字符串 C++ 中转换 Long? [复制]
【发布时间】:2011-11-21 12:12:45
【问题描述】:

可能重复:
C++ long to string
Easiest way to convert int to string in C++

我习惯了 Java,我几乎可以在任何东西上使用 .toString(),但我正在尝试 C++ 中的一些问题

我不知道如何将long 值转换为string

【问题讨论】:

    标签: c++ string


    【解决方案1】:

    您可以使用字符串流:

    #include <sstream>
    #include <string>
    
    long x;
    // ...
    std::ostringstream ss;
    ss << x;
    
    std::string result = ss.str();
    

    或者你可以使用Boost的lexical_cast

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

    我认为这是一个common opinion,该语言的这方面并没有它可以的那么优雅。

    在新的 C++11 中,事情稍微简单了一点,可以使用std::to_string() 函数:

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

    【讨论】:

    • 为完整性添加了另一个标准解决方案 :) 另外,我注意到内联编辑会默默地跳过其他人的更改。
    • @RMF:感谢编辑,我不知道!也许不优雅的日子已经结束了!
    • @Seth:是的,这在以前的标准版本中不存在。此外,像 stoi()strtoull() 这样的逆运算在 C++11 中对 std::string 有重载。
    【解决方案2】:
    #include <string>
    #include <sstream>
    
    std::ostringstream ss;
    long i = 10;
    ss << i;
    std::string str = ss.str();
    

    【讨论】:

      【解决方案3】:

      您可以使用字符串流。

      std::ostringstream ss;
      ss << aLongNumber;
      ss.str()
      

      您使用运算符&lt;&lt;,例如iostream coutcin。而你使用str() 方法来获取字符串。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2016-04-06
        • 1970-01-01
        • 2012-03-01
        • 1970-01-01
        • 1970-01-01
        • 2023-03-22
        • 2010-10-31
        相关资源
        最近更新 更多