Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Best way to cast numbers into strings in C++? [duplicate]

Coming from a C# background, In C# I could write this:

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

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

..and the casting to strings is implicit. In C++ I understand the casting has to be explicit, and I was wondering how the problem was usually tackled by a C++ programmer?

There's plenty of info on the net already I know, but there seems to quite a number of ways to do it and I was wondering if there wasn't a standard practice in place?

If you were to write that above code in C++, how would you do it?

like image 414
LynchDev Avatar asked Dec 12 '22 08:12

LynchDev


2 Answers

Strings in C++ are just containers of bytes, really, so we must rely on additional functionality to do this for us.

In the olden days of C++03, we'd typically use I/O streams' built-in lexical conversion facility (via formatted input):

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

std::stringstream ss;
ss << "words" << int1 << double1 << float1;

std::string str = ss.str();

You can use various I/O manipulators to fine-tune the result, much as you would in a sprintf format string (which is still valid, and still seen in some C++ code).

There are other ways, that convert each argument on its own then rely on concatenating all the resulting strings. boost::lexical_cast provides this, as does C++11's 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);

This latter approach doesn't give you any control over how the data is represented, though (demo).

  • std::stringstream
  • std::to_string
like image 84
Lightness Races in Orbit Avatar answered Dec 26 '22 04:12

Lightness Races in Orbit


If you can use Boost.LexicalCast (available for C++98 even), then it's pretty straightforward:

#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.

Note that as of C++11, you can also use std::to_string as mentioned by @LigthnessRacesinOrbit.

like image 23
TemplateRex Avatar answered Dec 26 '22 04:12

TemplateRex