Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert int8_t to std::string

Tags:

c++

c++98

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)
like image 420
Baz Avatar asked Feb 20 '26 02:02

Baz


1 Answers

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

like image 87
111111 Avatar answered Feb 22 '26 15:02

111111



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!