You want to do:
template <typename T>
std::string numberToString(T number) {
std::ostringstream ss;
ss << number;
return ss.str();
}
int main() {
std::cout << numberToString(123);
return 0;
}
To get the underlying std::string
in std::ostringstream
, and then the resulting c-style string in std::string
. As others have pointed out, the pointer returned by c_str
goes out of scope, and therefore you must copy it to a buffer or to another std::string
. If you insist on using printf
, then use c_str
on the function call:
printf("%s", numberToString(123).c_str());
For more information, see Is it a good idea to return " const char * " from a function?Is it a good idea to return " const char * " from a function?
Depending on what somestlstring is and what is being done there.
If it is a local variable you are returning a pointer into memory that is being released when GetSomeString completes, so it is a dangling pointer and an error.
It all boils down to the lifetime of somestlstring and the operations you perform on it. The pointer returned by .c_str() is guaranteed to be valid only up to the next mutating operation in the string. So if something changes somestlstring from the call to .c_str() and before s is constructed you will be in undefined behavior land.
However, you can simply use std::to_string
.
std::string s = std::to_string(123);