简体   繁体   English

如何从 int 转换为 char*?

[英]how to convert from int to char*?

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:在 C++17 中,使用std::to_chars作为:

     std::array<char, 10> str; std::to_chars(str.data(), str.data() + str.size(), 42);
  • In C++11, use std::to_string as:在 C++11 中,使用std::to_string作为:

     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:而在 C++03 中,你所做的一切都很好,除了使用const作为:

     char const* pchar = temp_str.c_str(); //dont use cast

I think you can use a sprintf :我认为您可以使用 sprintf :

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

You can use boost你可以使用升压

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

C-style solution could be to useitoa , but better way is to print this number into string by using sprintf / snprintf . C 风格的解决方案可能是使用itoa ,但更好的方法是使用sprintf / snprintf将此数字打印成字符串。 Check this question: How to convert an integer to a string portably?检查这个问题:如何将整数转换为可移植的字符串?

Note thatitoa function is not defined in ANSI-C and is not part of C++, but is supported by some compilers.注意itoa函数没有在 ANSI-C 中定义,也不是 C++ 的一部分,但被一些编译器支持。 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++?也检查这个问题: Alternative to itoa() for convert 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".还要注意,在用 C++ 编程时编写 C 风格的代码被认为是不好的做法,有时被称为“可怕的风格”。 Do you really want to convert it into C-style char* string?你真的想把它转换成 C 风格的char*字符串吗? :) :)

I would not typecast away the const in the last line since it is there for a reason.我不会对最后一行中的 const 进行类型转换,因为它存在是有原因的。 If you can't live with a const char* then you better copy the char array like:如果你不能忍受 const char* 那么你最好复制 char 数组,如:

char* char_type = new char[temp_str.length()];
strcpy(char_type, temp_str.c_str());

See this answer https://stackoverflow.com/a/23010605/2760919请参阅此答案https://stackoverflow.com/a/23010605/2760919

For your case, just change the type in snprintf from long ("%ld") to int ("%n").对于您的情况,只需将 snprintf 中的类型从 long ("%ld") 更改为 int ("%n")。

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!!!不幸的是,“更好”的方式是近 600 行代码!!! Pardon the name of it that doesn't have anything to do with what it's doing.原谅它的名字与它正在做的事情没有任何关系。 Proper name was Integer64ToCharArray(int64_t value);专有名称是Integer64ToCharArray(int64_t value);

https://github.com/JeremyDX/All-Language-Testing-Code/blob/master/C%2B%2B%20Examples/IntegerToCharArrayTesting.cpp 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.输入:从最小到最大范围的任何有符号 64 位值。

Example:例子:

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

Output:输出:

Test: 9223372036854775807
Test: -9223372036854775808

Original Speed Tests: ( Integer64ToCharArray(); )原始速度测试:( Integer64ToCharArray();

Best case 1 digit value.最佳情况 1 位数字值。

Loops: 100,000,000, Time Spent: 1,381(Milli), Time Per Loop 13(Nano)循环次数:100,000,000,花费时间:1,381(Milli),每循环时间 13(Nano)

Worse Case 20 Digit Value.更坏的情况 20 位数字值。

Loops: 100,000,000, Time Spent: 22,656(Milli), Time Per Loop 226(Nano循环次数:100,000,000,花费时间:22,656(Milli),每循环时间 226(Nano)

New Design Speed Tests: ( AddDynamicallyToBuffer(); )新的设计速度测试:( AddDynamicallyToBuffer();

Best case 1 digit value.最佳情况 1 位数字值。

Loops: 100,000,000, Time Spent: 427(Milli), Time Per Loop 4(Nano)循环次数:100,000,000,花费时间:427(Milli),每循环时间 4(Nano)

32 Bit Worst Case - 11 digit Value. 32 位最坏情况 - 11 位数值。

Loops: 100,000,000, Time Spent: 1,991(Milli), Time Per Loop 19(Nano)循环次数:100,000,000,花费时间:1,991(Milli),每循环时间 19(Nano)

Negative 1 Trillion Worst Case - 14 digit Value.负 1 万亿最坏情况 - 14 位数值。

Loops: 100,000,000, Time Spent: 5,681(Milli), Time Per Loop 56(Nano)循环次数:100,000,000,花费时间:5,681(Milli),每循环时间 56(Nano)

64 Bit Worse Case - 20 Digit Value. 64 位更坏情况 - 20 位数值。

Loops: 100,000,000, Time Spent: 13,148(Milli), Time Per Loop 131(Nano)循环次数:100,000,000,花费时间:13,148(Milli),每循环时间 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.在我的用法中,因此名称我返回偏移量,我不编辑字符数组的缓冲区,而是开始更新顶点数据,并且该函数有一个额外的偏移参数,因此它没有初始化为-1。

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.在 C++17 中使用“charconv”库解决了转换为 char 的问题。

https://en.cppreference.com/w/cpp/utility/to_chars https://en.cppreference.com/w/cpp/utility/to_chars

You also can use casting.您也可以使用铸造。

example:例子:

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

Converting our integer value to std::string so we can know how long (how long number of digits).将我们的整数值转换为 std::string 以便我们知道多长(多长的位数)。

Then we creating char array length of string letter size +1, so we can copy our value to string then char array.然后我们创建字符串字母大小 +1 的字符数组长度,所以我们可以将我们的值复制到字符串然后字符数组。

#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;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM