如何从int转换为char*?

rsk*_*k82 93 c++ integer const-char

我知道的唯一方法是:

#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();
}
Run Code Online (Sandbox Code Playgroud)

但是有没有更少打字的方法?

Naw*_*waz 120


小智 10

我想你可以使用sprintf:

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

  • 一些解释怎么样?`(((sizeof number)*CHAR_BIT)+ 2)/ 3 + 2`看起来像巫术...... (8认同)

mav*_*rik 7

你可以使用提升

#include <boost/lexical_cast.hpp>
string s = boost::lexical_cast<string>( number );
Run Code Online (Sandbox Code Playgroud)


Lih*_*ihO 5

可以使用C风格的解决方案itoa,但更好的方法是使用sprintf/snprintf将此数字打印到字符串中.检查这个问题:如何将整数转换为可移植的字符串?

请注意,itoa函数未在ANSI-C中定义,并且不是C++的一部分,但是某些编译器支持.这是一个非标准功能,因此您应该避免使用它.也检查这个问题:替换itoa()将整数转换为字符串C++?

还要注意在C++编程时编写C风格的代码被认为是不好的做法,有时也被称为"可怕的风格".你真的想把它转换成C风格的char*字符串吗?:)


use*_*471 5

我不会在最后一行中删除const,因为它是有原因的.如果你不能使用const char*那么你最好复制char数组,如:

char* char_type = new char[temp_str.length()];
strcpy(char_type, temp_str.c_str());
Run Code Online (Sandbox Code Playgroud)