C++ 如何从 int 转换为 char*?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/10847237/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
how to convert from int to char*?
提问by rsk82
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 ?
但是有什么方法可以减少打字吗?
回答by Nawaz
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
在 C++17 中,
std::to_chars
用作:std::array<char, 10> str; std::to_chars(str.data(), str.data() + str.size(), 42);
在 C++11 中,
std::to_string
用作:std::string s = std::to_string(number); char const *pchar = s.c_str(); //use char const* as target type
而在 C++03 中,你所做的一切都很好,除了
const
用作:char const* pchar = temp_str.c_str(); //dont use cast
回答by Pierre Pellegrino Milza
I think you can use a sprintf :
我认为您可以使用 sprintf :
int number = 33;
char* numberstring[(((sizeof number) * CHAR_BIT) + 2)/3 + 2];
sprintf(numberstring, "%d", number);
回答by maverik
You can use boost
你可以使用升压
#include <boost/lexical_cast.hpp>
string s = boost::lexical_cast<string>( number );
回答by LihO
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?
C 风格的解决方案可能是使用itoa
,但更好的方法是使用sprintf
/snprintf
将此数字打印成字符串。检查这个问题:如何将整数转换为可移植的字符串?
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++?
请注意,itoa
函数未在 ANSI-C 中定义,也不是 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". Do you really want to convert it into C-style char*
string? :)
还要注意,在用 C++ 编程时编写 C 风格的代码被认为是不好的做法,有时被称为“可怕的风格”。你真的想把它转换成 C 风格的char*
字符串吗?:)
回答by user331471
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:
我不会对最后一行中的 const 进行类型转换,因为它存在是有原因的。如果你不能忍受 const char* 那么你最好复制 char 数组,如:
char* char_type = new char[temp_str.length()];
strcpy(char_type, temp_str.c_str());
回答by Jeremy Trifilo
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);
好吧..首先我需要一些可以完成这个问题所要求的东西,但我需要它快!不幸的是,“更好”的方式是近 600 行代码!!!原谅它的名字与它正在做的事情没有任何关系。专有名称是Integer64ToCharArray(int64_t value);
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。
回答by bonnyz
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")。
回答by elmaystro
You also can use casting.
您也可以使用铸造。
example:
例子:
string s;
int value = 3;
s.push_back((char)('0' + value));
回答by AKJ
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 的问题。