在C++中将数字转换为字符串的最佳方法是什么?

4

作为来自C#背景的人,在C#中我可以这样写:

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

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

字符串转换是隐式的。在C++中,我知道强制类型转换必须是显式的,我想知道一个C++程序员通常如何解决这个问题?

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

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

4个回答

7

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操作符来微调结果,就像在格式字符串中一样(该格式字符串仍然有效,并且在某些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);

这种方法不会控制数据的表现形式 (演示)。如果想要更多控制,可以使用以下两种方法:

1
我们应该将其关闭为完全重复,而不是...? - legends2k
@legends2k:那不是完全重复的。 - Lightness Races in Orbit

4
如果你能使用 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;
}

实时示例

请注意,自C++11以来,您也可以使用std::to_string,如@LigthnessRacesinOrbit所提到的。


2
作为一名C开发人员,我会使用C字符串函数,因为它们在C++中也是完全有效的,并且可以让您对数字的格式(例如:整数、浮点数等)非常明确地进行格式化。在这种情况下,您需要使用`sprintf()`或`snprintf()`函数。格式说明符使您的意图在源代码中非常明显。
参考链接:http://www.cplusplus.com/reference/cstdio/printf/

0
在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;     
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接