将非空终止的无符号字符数组复制到 std::string [英] Copying non null-terminated unsigned char array to std::string

查看:24
本文介绍了将非空终止的无符号字符数组复制到 std::string的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果数组是空终止,这将非常简单:

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::string.

有没有什么方法可以不用迭代无符号字符数组?

Is there any way to do it without iterating over the unsigned char array?

谢谢大家.

推荐答案

std::string 有一个 constructor 接受一对迭代器和 unsigned char 可以(以实现定义的方式)转换为 char> 所以这是有效的.不需要 reinterpret_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计算更健壮.

Of course an "array size" template function is more robust than the sizeof calculation.

这篇关于将非空终止的无符号字符数组复制到 std::string的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆