how to convert from int to char*?

前端 未结 10 2040
旧巷少年郎
旧巷少年郎 2020-11-30 18:37

The only way I know is:

#include 
#include 
using namespace std;

int main() {
  int number=33;
  stringstream strs;
  strs &l         


        
相关标签:
10条回答
  • 2020-11-30 18:54

    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

    0 讨论(0)
  • 2020-11-30 18:55

    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());
    
    0 讨论(0)
  • 2020-11-30 18:58

    You also can use casting.

    example:

    string s;
    int value = 3;
    s.push_back((char)('0' + value));
    
    0 讨论(0)
  • 2020-11-30 19:01

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

    0 讨论(0)
  • 2020-11-30 19:02
    • 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
      
    0 讨论(0)
  • 2020-11-30 19:04

    I think you can use a sprintf :

    int number = 33;
    char* numberstring[(((sizeof number) * CHAR_BIT) + 2)/3 + 2];
    sprintf(numberstring, "%d", number);
    
    0 讨论(0)
提交回复
热议问题