2

I have a vector of chars (actually unsigned chars):

std::vector<unsigned char> vec;

I would like to cast it/ copy it to a string object. I have tried to do this in the following way:

std::string requestedName;

for (auto letter : vec)
{
    requestedName.append((char)letter);
}

But compiller says that such conversion is not possible. I would aprichiate all help.

Łukasz Przeniosło
  • 2,725
  • 5
  • 38
  • 74

1 Answers1

5

You can use the operator += to perform this concatenation

std::vector<unsigned char> vec {'a', 'b', 'c', 'd'};
std::string requestedName;
for (auto letter : vec)
    requestedName += letter;

Working demo

Also instead of concatenating in a loop, you can use the following overload of the std::string constructor

std::vector<unsigned char> vec {'a', 'b', 'c', 'd'};
std::string requestedName{ vec.begin(), vec.end() };
Cory Kramer
  • 114,268
  • 16
  • 167
  • 218
  • 1
    I can't see any reason to use the unnecessarily inefficient concatenation approach. – juanchopanza Jun 11 '15 at 13:08
  • 1
    @juanchopanza Neither can I, which is why I recommended using the constructor. I was just noting that `operator+=` would fix how they were trying to `append` to the string. – Cory Kramer Jun 11 '15 at 13:09
  • If the `std::vector vec` initilized with interger like `std::vector vec {0, 1, 2, 3};`, the output is blank, any good idea to solve this ? – Wade Wang Jun 29 '21 at 02:58