The only way I know is:
#include
#include
using namespace std;
int main() {
int number=33;
stringstream strs;
strs &l
This might be a bit late, but i also had the same issue. Converting to char was addressed in C++17 with the "charconv" library.
https://en.cppreference.com/w/cpp/utility/to_chars
I would not typecast away the const in the last line since it is there for a reason. If you can't live with a const char* then you better copy the char array like:
char* char_type = new char[temp_str.length()];
strcpy(char_type, temp_str.c_str());
You also can use casting.
example:
string s;
int value = 3;
s.push_back((char)('0' + value));
C-style solution could be to use itoa, but better way is to print this number into string by using sprintf / snprintf. Check this question: How to convert an integer to a string portably?
Note that itoa function is not defined in ANSI-C and is not part of C++, but is supported by some compilers. It's a non-standard function, thus you should avoid using it. Check this question too: Alternative to itoa() for converting integer to string C++?
Also note that writing C-style code while programming in C++ is considered bad practice and sometimes referred as "ghastly style". Do you really want to convert it into C-style char*
string? :)
In C++17, use std::to_chars as:
std::array<char, 10> str;
std::to_chars(str.data(), str.data() + str.size(), 42);
In C++11, use std::to_string as:
std::string s = std::to_string(number);
char const *pchar = s.c_str(); //use char const* as target type
And in C++03, what you're doing is just fine, except use const
as:
char const* pchar = temp_str.c_str(); //dont use cast
I think you can use a sprintf :
int number = 33;
char* numberstring[(((sizeof number) * CHAR_BIT) + 2)/3 + 2];
sprintf(numberstring, "%d", number);