在你点踩之前请仔细阅读,这里有些有趣的内容。基本上我想要将一个类型为
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
和char
和std::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;
'0'
和'1'
,而不是整数0
和1
。 - Bo Persson