【问题标题】:Converting an array of chars to std::string in order to pass into std::bitset seg fault将字符数组转换为 std::string 以传递到 std::bitset 段错误
【发布时间】:2017-05-27 05:09:30
【问题描述】:

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

在抛出 'std::invalid_argument' 的实例后调用终止 what(): bitset::_M_copy_from_ptr 中止(核心转储)

这是代码

#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 构造函数,我都会得到相同的错误?

这些只是我从上面的代码中注释掉并删除的 sn-ps,以显示我尝试过的内容。

//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;

【问题讨论】:

  • 字符串应该包含字符'0''1',而不是整数01

标签: c++ string char type-conversion bitset


【解决方案1】:

这是错误的:

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)。

【讨论】:

  • 是的,试过了,但为什么呢?如果我将 char 初始化为零,为什么不是 1?
  • @pandoragami:我想你没能理解字符'0'和数字0之间的区别。 asciitable.com
  • 所以我不能使用 'start of heading' 或 NULL 作为值,但我应该可以使用 48 或 49?
  • 文档很清楚:字符串只能包含ASCII字符'0''1'。不允许 SOH。
【解决方案2】:

std::string 构造自

char BYTE_4[4] = { 1, 0, 0, 0};

与构造自的std::string 没有什么不同

char BYTE_4[4] = { 1, '\0', '\0', '\0'};

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

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

你可以使用:

char BYTE_4[] = {'1', '0', '0', '0', '\0'};
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 位为 0,后 4 位为 1000。

【讨论】:

    猜你喜欢
    • 2019-10-24
    • 2013-10-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-01-28
    相关资源
    最近更新 更多