[C++] strings and short ints...

Started by
2 comments, last by theSecondt 17 years, 6 months ago
For beginners? oh, good. i have a problem with getting the values from a short int type var into a std::string string. i tried the following(+ with static_cast<char>):
Quote: short ffps= getFPS(); std::string bla; bla.clear(); bla+= ffps;
but to no avail. thanks.
Advertisement
In STL there is no coercion support between strings and numbers. Use the std::stringstream:
#include <sstream>#include <string>std::stringstream s;s << getFPS();// To get the std::string call str() on the std::stringstreamstd::cout << s.str();


Greetz,

Illco
operator+= for std::string only accepts characters, C-style strings, or std::strings. If you want to convert an integer to a string, you can use std::stringstream:

std::stringstream  convert;short              number = 38;  convert << number;std::string result = convert.str();


Then you can use result. You can also use stringstreams to convert other other way, if you'd like.

Later on in your career, look into boost::lexical_cast, which provides the same functionality but in a cleaner package. You may not quite be ready for Boost, yet. It can be daunting...
oh, lol.
i used sstream just before i got into this little trouble.

thank you, and i'll look into boost, since i've heard so much about it already.

This topic is closed to new replies.

Advertisement