复制非空值终止的无符号字符数组为std :: string [英] Copying non null-terminated unsigned char array to std::string
问题描述
如果阵列的空值终止的,这将是pretty直截了当:
If the array was null-terminated this would be pretty straight forward:
unsigned char u_array[4] = { 'a', 's', 'd', '\0' };
std::string str = reinterpret_cast<char*>(u_array);
std::cout << "-> " << str << std::endl;
不过,我不知道什么是复制的非空值终止无符号字符数组,像下面的最合适的方式:
However, I wonder what is the most appropriate way to copy a non null-terminated unsigned char array, like the following:
unsigned char u_array[4] = { 'a', 's', 'd', 'f' };
到的std ::字符串
。
有没有办法做到这一点不遍历的无符号的字符数组的?
Is there any way to do it without iterating over the unsigned char array?
感谢大家。
推荐答案
的std ::字符串
拥有的构造,需要一个对迭代器和 unsigned char型
可转换(在实施定义的方式),以字符
所以此工程。没有必要为一个 reinter pret_cast
。
std::string
has a constructor that takes a pair of iterators and unsigned char
can be converted (in an implementation defined manner) to char
so this works. There is no need for a reinterpret_cast
.
unsigned char u_array[4] = { 'a', 's', 'd', 'f' };
#include <string>
#include <iostream>
#include <ostream>
int main()
{
std::string str( u_array, u_array + sizeof u_array / sizeof u_array[0] );
std::cout << str << std::endl;
return 0;
}
当然是一个数组大小模板函数比的sizeof
计算更加强劲。
这篇关于复制非空值终止的无符号字符数组为std :: string的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!