how to convert from int to char*?

C++IntegerConst Char

C++ Problem Overview


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 ?

C++ Solutions


Solution 1 - C++

  • 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
    

Solution 2 - C++

I think you can use a sprintf :

int number = 33;
char* numberstring[(((sizeof number) * CHAR_BIT) + 2)/3 + 2];
sprintf(numberstring, "%d", number);

Solution 3 - C++

You can use boost

#include <boost/lexical_cast.hpp>
string s = boost::lexical_cast<string>( number );

Solution 4 - C++

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: https://stackoverflow.com/q/2225868/1168156

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: https://stackoverflow.com/q/228005/1168156

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? :)

Solution 5 - C++

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());

Solution 6 - C++

Alright.. firstly I needed something that did what this question is asking, but I needed it FAST! Unfortunately the "better" way is nearly 600 lines of code!!! Pardon the name of it that doesn't have anything to do with what it's doing. Proper name was Integer64ToCharArray(int64_t value);

https://github.com/JeremyDX/All-Language-Testing-Code/blob/master/C%2B%2B%20Examples/IntegerToCharArrayTesting.cpp

Feel free to try cleaning that code up without hindering performance.

Input: Any signed 64 bit value from min to max range.

Example:

std::cout << "Test: " << AddDynamicallyToBuffer(LLONG_MAX) << '\n';
std::cout << "Test: " << AddDynamicallyToBuffer(LLONG_MIN) << '\n';

Output:

Test: 9223372036854775807
Test: -9223372036854775808

Original Speed Tests: (Integer64ToCharArray();)

Best case 1 digit value.

> Loops: 100,000,000, Time Spent: 1,381(Milli), Time Per Loop 13(Nano)

Worse Case 20 Digit Value. > Loops: 100,000,000, Time Spent: 22,656(Milli), Time Per Loop 226(Nano

New Design Speed Tests: (AddDynamicallyToBuffer();)

Best case 1 digit value. > Loops: 100,000,000, Time Spent: 427(Milli), Time Per Loop 4(Nano)

32 Bit Worst Case - 11 digit Value. > Loops: 100,000,000, Time Spent: 1,991(Milli), Time Per Loop 19(Nano)

Negative 1 Trillion Worst Case - 14 digit Value. > Loops: 100,000,000, Time Spent: 5,681(Milli), Time Per Loop 56(Nano)

64 Bit Worse Case - 20 Digit Value. > Loops: 100,000,000, Time Spent: 13,148(Milli), Time Per Loop 131(Nano)

How It Works!

We Perform a Divide and Conquer technique and once we now the maximum length of the string we simply set each character value individually. As shown in above speed tests the larger lengths get big performance penalties, but it's still far faster then the original loop method and no code has actually changed between the two methods other then looping is no longer in use.

In my usage hence the name I return the offset instead and I don't edit a buffer of char arrays rather I begin updating vertex data and the function has an additional parameter for offset so it's not initialized to -1.

Solution 7 - C++

See this answer https://stackoverflow.com/a/23010605/2760919

For your case, just change the type in snprintf from long ("%ld") to int ("%n").

Solution 8 - C++

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

Solution 9 - C++

You also can use casting.

example:

string s;
int value = 3;
s.push_back((char)('0' + value));

Solution 10 - C++

Converting our integer value to std::string so we can know how long (how long number of digits).

Then we creating char array length of string letter size +1, so we can copy our value to string then char array.

#include <string>

char* intToStr(int data) {
    std::string strData = std::to_string(data);

    char* temp = new char[strData.length() + 1];
    strcpy(temp, strData.c_str());

   return temp;
}

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
Questionrsk82View Question on Stackoverflow
Solution 1 - C++NawazView Answer on Stackoverflow
Solution 2 - C++Pierre PellegrinoView Answer on Stackoverflow
Solution 3 - C++maverikView Answer on Stackoverflow
Solution 4 - C++LihOView Answer on Stackoverflow
Solution 5 - C++user331471View Answer on Stackoverflow
Solution 6 - C++Jeremy TrifiloView Answer on Stackoverflow
Solution 7 - C++bonnyzView Answer on Stackoverflow
Solution 8 - C++AKJView Answer on Stackoverflow
Solution 9 - C++elmaystroView Answer on Stackoverflow
Solution 10 - C++EmrexdyView Answer on Stackoverflow