4
string temp;
temp = line.substr(0, pos);

I need to convert the string temp to an unsigned char array. Could someone please tell me how this can be done? I tried the methods mentioned in the below link but they didn't work.

How to convert a string literal to unsigned char array in visual c++

unsigned char* val=new[temp.size() + 1](); //Error: Expected a type.
copy(temp.begin(), temp.end(), val);
4
  • if you just need access to the underlying char array you can use .c_str() but that doesn't guarantee unsigned. Why don't the methods in that other question work for you? Commented Feb 18, 2015 at 17:54
  • 1
    Just to be sure, you want an unsigned char array, right? Not just an unsigned char? Commented Feb 18, 2015 at 17:55
  • What exactly are you trying to get out of this "conversion"? If the string is "abcde", what should be the result? Commented Feb 18, 2015 at 17:55
  • Sorry I just edited the description. Commented Feb 18, 2015 at 18:02

1 Answer 1

10

It is ugly to put a string in a raw unsigned char buffer and you should not do that, but this is stack overflow and we have to answer.

unsigned char *val=new unsigned char[temp.length()+1];
strcpy((char *)val,temp.c_str());
Sign up to request clarification or add additional context in comments.

3 Comments

why is it ugly? Can you please tell me a better way to do? I have Vector<uchar> colors. I am getting strings by reading the file. I need to insert these string into "colors". please tell me if there is a cleaner way to achieve this.
@aries It is ugly to put a string in a unsigned char array. You should use std::vector. The answer is okay, your question implies that you want to do something which will not be okay. (But you didn't tell)
@aries Get the code running with the piece I provided. Then ask a new question how to do it better. Your question in the comment exceed what a comment should provide in the first place. It should be part of the question (with more code).

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.