字符串和字符元素
问题描述:
我有一个unsigned char* c
包含元素0x1c。我如何将它添加到std::vector<unsigned char>vect
?我正在使用C++。字符串和字符元素
std::vector<unsigned char>vect; //the vect dimention is dynamic
std::string at="0x1c";
c=(unsigned char*)(at.c_str());
vect[1]=c //error? why?
答
你有一个字符串中的一个字符的十六进制表示,你想要的字符?
最简单的:
unsigned char c;
istringstream str(at);
str >> hex >> c; // force the stream to read in as hex
vect.push_back(c);
(我认为这应该工作,没有测试过)
我只是再次重读你的问题,这条线:
I have an unsigned char* c that contains the element 0x1c
不这意味着实际上你的unsigned char *看起来像这样:
unsigned char c[] = {0x1c}; // i.e. contains 1 byte at position 0 with the value 0x1c?
以上我的假设......
打印矢量出来cout
,使用一个简单的for循环,或如果你感觉勇敢
std::cout << std::ios_base::hex;
std::copy(vect.begin(), vect.end(), std::ostream_iterator<unsigned char>(std::cout, " "));
std::cout << std::endl;
这将打印向量中由空格分隔的每个unsigned char
值的十六进制表示。
答
c是unsigned char*
。 vect是std::vector<unsigned char>
,所以它包含无符号的char值。作业将失败,因为operator []
在std::vector<unsigned char>
预计unsigned char
,而不是unsigned char *
。
答
//The vect dimension is dynamic ONLY if you call push_back
std::vector <std::string> vect;
std::string at="0x1c";
vect.push_back(at);
如果您使用的是C++,请使用std :: string。上面的代码会将你的“0x1c”字符串复制到向量中。
如果你尝试做
vect[0] = c;
如果不先用
vect.resize(1);
拓展载体,你会得到分段错误,因为操作符[]不动态扩展矢量。矢量的初始大小是0 btw。
UPDATE:根据OP的评论,这里就是他所希望的:复制一个无符号字符*到一个std ::向量(iecopying C数组到C++向量)
std::string at = "0x1c";
unsigned char * c = (unsigned char*)(at.c_str());
int string_size = at.size();
std::vector <unsigned char> vect;
// Option 1: Resize the vector before hand and then copy
vect.resize(string_size);
std::copy(c, c+string_size, vect.begin());
// Option 2: You can also do assign
vect.assign(c, c+string_size);
我会说错误是因为vect [1]是一个无符号字符,而c是一个指针。也许`vect [1] = * c`?尽管如此,我还没有用过C++。 – Tesserex 2011-01-19 15:11:43
注意:如果要设置第一个值,您可能需要`vect [0]`而不是`vect [1]`。另外,你真的得到了什么错误? – Maxpm 2011-01-19 15:12:43
我有分段错误:( – elisa 2011-01-19 15:15:11