Question

Is this correct for all C++ compilers? Or should I cast to int first instead?

int8_t i = -128; 
std::string = boost::lexical_cast<std::string>((int16_t)i)
Was it helpful?

Solution

You can use the std::to_string function to do this:

 std::int8_t i = -128; 
 std::string s=std::to_string(i);

http://en.cppreference.com/w/cpp/string/basic_string/to_string

NOTE:

I assumed C++11 because fixed width types where only added in C++11

http://en.cppreference.com/w/cpp/types/integer

edit

If this is not C++11 (and you are getting the typedef form somewhere else (C99?)) then you can just provide the source type as a template parameter.

 std::string str=boost::lexical_cast<std::string, int>(i);

http://www.boost.org/doc/libs/1_40_0/libs/conversion/lexical_cast.htm#synopsis

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top