将字符数组转换为 std::string 以传递到 std::bitset 段错误

Converting an array of chars to std::string in order to pass into std::bitset seg fault

在投反对票之前请仔细阅读,它确实很有趣。基本上我想将类型 char 数组转换为 std::string 以便使用 std::bitset 操作但是当我尝试在运行时创建 bitset 对象时我得到这个错误。

terminate called after throwing an instance of 'std::invalid_argument' what(): bitset::_M_copy_from_ptr Aborted (core dumped)

这是代码

#include <iostream>
#include <cstdlib>
#include <bitset>

int main()
{
    char BYTE_4[4] = { 1, 0, 0, 0};

    std::string str_BYTE_4 = std::string(BYTE_4);

    std::bitset<32> str_BYTE_4_bit( str_BYTE_4);//crash here
    std::cout<<"str_BYTE_4_bit. "<<str_BYTE_4_bit<<std::endl;

    return 0;
}

我还尝试了一些其他类型的转换 std::stringstream 以及 charstd::string 的指针,无论我将什么传递给 std::bitset 构造函数,我都会得到同样的错误?

这些只是我从上面的代码中注释掉并删除的片段,以展示我的尝试。

//char* BYTE_4 = new char[4];
    //std::stringstream SS;

    //std::string str_BYTE_4 = "0101";
    //SS << BYTE_4;
        //str_BYTE_4 = SS.str();
    //for(int index = 0; index < 4; index++)
        //    str_BYTE_4 += BYTE_4[index];

    //std::string *str_BYTE_4 = new std::string[4];
    //for( int index = 0; index < 4; index++)
        //    BYTE_4[index] = rand()%255;

这是错误的:

char BYTE_4[4] = { 1, 0, 0, 0};
std::string str_BYTE_4 = std::string(BYTE_4);

您需要的是一串数字,但您存储的是原始字节 10(不是 ASCII“1”和“0”)。像这样修复它:

char BYTE_4[4] = { '1', '0', '0', '0'};
std::string str_BYTE_4 = std::string(BYTE_4, sizeof(BYTE_4));

由于没有空终止符,您必须告诉 std::string 构造函数在何处停止(通过将 4 作为第二个参数传递)。

一个更简单的方法是:

std::string str_BYTE_4 = "1000";

至于你得到的 invalid_argument 异常,如果你阅读 bitset 的文档,你会发现这意味着你传递了一个字符串,其中包含一个既不是 '0' 的字符也不是 '1'(那些是 ASCII 字符,其原始整数值为 48 和 49)。

构造的std::string
char BYTE_4[4] = { 1, 0, 0, 0};

与从

构造的std::string没有什么不同
char BYTE_4[4] = { 1, '[=11=]', '[=11=]', '[=11=]'};

您只有 charstd:string 中的整数值 1 表示。这就是问题的根源。

为了能够从 std::string 构造 std::bitset,您需要 std::string 仅包含字符 '1''0' .因此,您需要使用字符 '1''0',而不是整数值 10.

您可以使用:

char BYTE_4[] = {'1', '0', '0', '0', '[=12=]'};
std::string str_BYTE_4 = std::string(BYTE_4);

char BYTE_4[4] = {'1', '0', '0', '0'};
std::string str_BYTE_4 = std::string(BYTE_4, 4);

为了能够从 std::string.

构造一个 std::bitset

物有所值:

std::bitset<32> str_BYTE_4_bit(std::string());

创建一个 bitset,其值由 32 个零位组成。

std::bitset<32> str_BYTE_4_bit(std::string("1000"));

创建一个bitset,其值由 28 个前导位组成,前导位为零,最后 4 位为 1000。