开发者

string and char elements

开发者 https://www.devze.com 2023-02-06 02:04 出处:网络
I have an 开发者_开发知识库unsigned char* c that contains the element 0x1c. How can I add it into an std::vector<unsigned char>vect? I am working in c++.

I have an 开发者_开发知识库unsigned char* c that contains the element 0x1c. How can I add it into an std::vector<unsigned char>vect? I am working in 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?


//The vect dimension is dynamic ONLY if you call push_back
std::vector <std::string> vect;  

std::string at="0x1c";
vect.push_back(at);

If you are using C++, use std::string. The above code will copy your "0x1c" string into the vector.

If you try to do

vect[0] = c;

Without first expanding the vector with

vect.resize(1);

You will get segmentation fault because operator[] doesn't expand the the vector dynamically. The initial size of a vector is 0 btw.

UPDATE: According to the OP's comment, here is what he would want: copying a unsigned char * to a std::vector (i.e.copying a C array to a C++ vector)

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


c is an unsigned char*. vect is a std::vector<unsigned char>, so it contains unsigned char values. The assignment will fail, as operator [] on std::vector<unsigned char> expects an unsigned char, not a unsigned char *.


You have a hex representation of a character in a string, and you want the character?

easiest:

unsigned char c;
istringstream str(at);
str >> hex >> c; // force the stream to read in as hex
vect.push_back(c);

(I think that should work, have not tested it)


I just reread your question again, this line:

I have an unsigned char* c that contains the element 0x1c

Does this mean that actually your unsigned char* looks like this:

unsigned char c[] = {0x1c}; // i.e. contains 1 byte at position 0 with the value 0x1c?

or my assumption above...


to print the vector out to cout, use a simple for loop, or if you are feeling brave

std::cout << std::ios_base::hex;

std::copy(vect.begin(), vect.end(), std::ostream_iterator<unsigned char>(std::cout, " "));

std::cout << std::endl;

this will print the hex representations of each of the unsigned char values in the vector separated by a space.

0

精彩评论

暂无评论...
验证码 换一张
取 消