Reputation: 3582
I have a string vector and a self declared type of unsigned char:
std::vector<std::string> result;
typedef unsigned char BYTE;
BYTE data[11];
I have assigned values to result. Now I want to copy the elements of result
into data
:
for ( int i=0; i<11; i++)
{
data[i] = result[i];
}
But it gives out error, saying No suitable conversion function from std::string to BYTE exists
.
How can I handle this?
Update:
First, thank you all for your precious comments and answers.
In my code, my result
is of six elements like these values:
0x30
0x31
0x32
0x33
0x34
0x35
I tried as Raxvan's answer, but at the end, data
only captures the first value of those string elements, that is, all zeros. What I actually want to do is to let data
have the same values as result
, but of BYTE
type, so that it is similar to assigning values like this:
BYTE data[] = { 0x30, 0x31, 0x32, 0x33, 0x34, 0x35 } // this line works correctly
Upvotes: 0
Views: 626
Reputation: 11787
Its long since I have written some CPP code, so kindly excuse for the syntax errors. I think what OP is trying to achieve is convert the 2D array to a single comma separated string.
Here is my sample code:
char [] DATA = "";
for ( int j = 0;j < result.count(); j++)
{
if(j < result.count()-2)
result = strcat(result, ",")
DATA = strcat(DATA, result);
}
Upvotes: 1
Reputation: 11428
You're confusing your types.
The data
is an array of BYTE (so basically able to hold 11 characters),
but result
is an array of string
(meaning it can hold multiple strings, each of those holding multiple characters).
So depending on what you actually need you can do two things:
If you need all strings to be converted into BYTE arrays, then create an array of arrays of BYTE:
// adapt sizes to your needs
size_t const MaxStrSize = 11; // allows to hold 10 characters (+ 0 delimiter)
size_t const MaxStrCount = 11;
BYTE data[MaxStrCount][MaxStrSize];
for (int j=0; j<MaxStrCount && j<result.size(); ++j)
{
for ( int i=0; i<MaxStrSize && i<result[i].length(); i++)
{
data[j][i] = result[j][i];
}
}
Otherwise, if you only want to access one of the strings contained in the vector (e.g. the first one): See Raxvan's answer.
Upvotes: 3
Reputation: 6515
string
encapsulates an array of char
and the compiler doesn't know how to convert that into one char. If you want to take the first character from the strings then you can do this:
for ( int i=0,j = 0; i<11 && j < result.size(); j++)
{
if(result[j].size() != 0) //safety first.
data[i++] = result[j][0];
}
Upvotes: 3