Reputation: 3103
Is there any function in C++ which converts all data types (double
, int
, short
, etc) to string
?
Upvotes: 4
Views: 3934
Reputation: 1186
For this use stringstream. First include the header file as #include . Then create an object of stringstream and using stream insertion operator (<<) pass the contents you want to convert as string. Ex:
#include <iostream>
#include <sstream>
int main(){
std::string name = "Ram";
float salary = 400.56;
std::stringstream obj;
obj << name << " salary: " << salary;
std::string s = obj.str();
std::cout << s;
}
Upvotes: 0
Reputation: 777
Here is the one I use from my utility library. This was condensed from other posts here on stackoverflow, I am not claiming this as my own original code.
#include <string>
#include <sstream>
using namespace std;
template <class T>
string ToString(const T& Value) {
stringstream ss;
ss << Value;
string s = ss.str();
return s;
}
also, another handy string formatting utility I use:
#include <string>
#include <stdarg.h> /* we need va_list */
// Usage: string myString = FormatString("%s %d", "My Number =", num);
string FormatString(const char *fmt, ...) {
string retStr;
if (NULL != fmt) {
va_list marker = NULL;
va_start(marker, fmt);
size_t len = 256 + 1; // hard size set to 256
vector <char> buffer(len, '\0');
if (vsnprintf(&buffer[0], buffer.size(), fmt, marker) > 0) {
retStr = &buffer[0]; // Copy vector contents to the string
}
va_end(marker);
}
return retStr;
}
Upvotes: 1
Reputation: 54600
There is no built-in universal function, but boost::lexical_cast<> will do this.
Upvotes: 2
Reputation: 96241
Why do you need this conversion? A lot of languages have variant types which auto-convert, and this can lead to wanting that behavior in C++ even though there may be a more canonical way of implementing it.
For example if you're trying to do output, using a (string)stream of some sort is probably the way to go. If you really need to generate and manipulate a string, you can use boost::lexical_cast
http://www.boost.org/doc/libs/1_43_0/libs/conversion/lexical_cast.htm.
Upvotes: 1
Reputation: 2259
If boost is not an option (it should always be, but just in case):
#include <sstream>
#include <string>
template<class T1, class T2>
T1 lexical_cast(const T2& value)
{
std::stringstream stream;
T1 retval;
stream << value;
stream >> retval;
return retval;
}
template<class T>
std::string to_str(const T& value)
{
return lexical_cast<std::string>(value);
}
Boost has a similar idea, but the implementation is much more efficient.
Upvotes: 3
Reputation: 51465
http://www.boost.org/doc/libs/1_43_0/libs/conversion/lexical_cast.htm
Upvotes: 4
Reputation: 2556
Usually you'll use the <<
operator, in conjunction with (for example) a std::stringstream.
Upvotes: 8