The only way I know is:
#include <sstream>
#include <string.h>
using namespace std;
int main() {
int number=33;
stringstream strs;
strs << number;
string temp_str = strs.str();
char* char_type = (char*) temp_str.c_str();
}
But is there any method with less typing ?
In C++17, use
std::to_chars
as:In C++11, use
std::to_string
as:And in C++03, what you're doing is just fine, except use
const
as:C-style solution could be to use
itoa
, but better way is to print this number into string by usingsprintf
/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? :)You also can use casting.
example:
Alright my way isn't exactly "less code" like you wanted, but I found the recommended ways to be way too slow for my usage.
Usage is simple:
This supports all numbers between 64bit MIN and MAX VALUES.
Something to keep in mind... I made the returned buffer static in the method. I set it to a size of 21 to ensure 21 bytes is allocated. Which is the maximum size a digits and negative and length index of LONG value can be. So this is safe to execute as many times as you'd like where as many other ways allocate new memory ever time they are called.
I needed something that would allow me to convert Integers to char arrays quickly so I could convert them into quads for font rendering. All the above methods are just far too slow for my needs. This should be able get the char value of 2500 numbers with up to 19 digits in under 1ms.
!!SPEED TESTS!!
Your Answer
Loops: 500,000, Time Spent: 5,428(Milli), Time Per Loop 10,856(Nano)
My Way Of Doing It
Best case 1 digit value.
Loops: 10,000,000, Time Spent: 493(Milli), Time Per Loop 49(Nano)
Worse Case 19 Digit Value.
Loops: 10,000,000, Time Spent: 2,192(Milli), Time Per Loop 219(Nano)
SprintF Way As Mentioned In Comments
Well doing sprintf_s was damn near the same.
Worse Case: Loops: 10000000, Time Spent: 3102(Milli), Time Per Loop 310(Nano)
Best Case: Loops: 10000000, Time Spent: 1189(Milli), Time Per Loop 118(Nano)
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:
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