【问题标题】:Best way to cast numbers into strings in C++? [duplicate]在 C++ 中将数字转换为字符串的最佳方法? [复制]
【发布时间】:2014-01-28 12:52:27
【问题描述】:

来自C# 背景,在C# 我可以这样写:

int int1       = 0;
double double1 = 0;
float float1   = 0;

string str = "words" + int1 + double1 + float1;

..并且转换为字符串是隐式的。在C++ 中,我知道强制转换必须是明确的,我想知道C++ 程序员通常如何解决这个问题?

我已经知道网上有很多信息,但似乎有很多方法可以做到这一点,我想知道是否没有标准做法?

如果您要在C++ 中编写上述代码,您会怎么做?

【问题讨论】:

    标签: c++ string c++11 casting numbers


    【解决方案1】:

    C++ 中的字符串实际上只是字节的容器,所以我们必须依靠额外的功能来为我们做这件事。

    在 C++03 的早期,我们通常使用 I/O 流的内置词法转换工具(通过格式化输入):

    int    int1    = 0;
    double double1 = 0;
    float  float1  = 0;
    
    std::stringstream ss;
    ss << "words" << int1 << double1 << float1;
    
    std::string str = ss.str();
    

    您可以使用各种 I/O 操纵器来微调结果,就像您在 sprintf 格式字符串中所做的一样(它仍然有效,并且在某些 C++ 代码中仍然可见)。

    还有其他方法,可以单独转换每个参数,然后依赖连接所有结果字符串。 boost::lexical_cast 提供了这一点,C++11 的 to_string 也是如此:

    int    int1    = 0;
    double double1 = 0;
    float  float1  = 0;
    
    std::string str = "words"
       + std::to_string(int1) 
       + std::to_string(double1) 
       + std::to_string(float1);
    

    尽管 (demo),后一种方法无法让您控制数据的表示方式。

    【讨论】:

    • 我们不应该把它作为一个完全的欺骗而不是......吗?
    • @legends2k:这不是一个完全的骗局。
    【解决方案2】:

    如果您可以使用 Boost.LexicalCast(甚至适用于 C++98),那么它非常简单:

    #include <boost/lexical_cast.hpp>
    #include <iostream>
    
    int main( int argc, char * argv[] )
    {
        int int1       = 0;
        double double1 = 0;
        float float1   = 0;
    
        std::string str = "words" 
                   + boost::lexical_cast<std::string>(int1) 
                   + boost::lexical_cast<std::string>(double1) 
                   + boost::lexical_cast<std::string>(float1)
        ;
    
        std::cout << str;
    }
    

    Live Example.

    请注意,从 C++11 开始,您还可以使用 @LigthnessRacesinOrbit 提到的 std::to_string

    【讨论】:

      【解决方案3】:

      作为一名 C 开发人员,我会使用 C 字符串函数,因为它们在 C++ 中完全有效,并且让您非常明确数字的格式(即:整数、浮点点等)。

      http://www.cplusplus.com/reference/cstdio/printf/

      在这种情况下,sprintf()snprintf() 就是您要查找的内容。格式说明符使源代码本身的意图也非常明显。

      【讨论】:

        【解决方案4】:

        在 C++ 中将数字转换为 std::string 的最佳方法是使用已有的。 库 sstream 为 std::string 提供流实现。 就像使用流(cout,cin)例如

        它易于使用: http://www.cplusplus.com/reference/sstream/stringstream/?kw=stringstream

        #include <sstream>
        using std::stringstream;
        #include <string>
        using std::string;
        #include <iostream>
        using std::cout;
        using std::endl;
        
        int main(){
           stringstream ss;
           string str;
           int i = 10;
        
           ss << i;
           ss >> str;
        
           cout << str << endl;     
        }
        

        【讨论】:

          猜你喜欢
          • 2018-05-28
          • 2014-06-21
          • 1970-01-01
          • 2010-10-21
          • 1970-01-01
          • 2017-11-08
          • 1970-01-01
          • 2011-04-06
          • 1970-01-01
          相关资源
          最近更新 更多