0

I have a

std::vector<unsigned char> data;

which contains a binary read file.

If I write it to

std::ofstream outputFile("file", std::ios_base::binary);

I'll see a regular text in it. Then I can read it into std::string which will conatain the text. Is it possible to copy vector directly to string with the same result?

w00drow
  • 468
  • 2
  • 11
  • Yes, `std::string s(data.begin(), data.end());` Or if you already have a string: `s.assign(data.begin(), data.end());` – Galik Sep 16 '15 at 14:54

2 Answers2

1

Use the 6th form of std::string's constructor:

// Example program
#include <iostream>
#include <string>
#include <vector>

int main()
{
    std::vector<unsigned char> data{'a', 'b', 'c'};
    std::string str(data.begin(), data.end());
    std::cout << str << std::endl;
}

Live demo here

anorm
  • 2,255
  • 1
  • 19
  • 38
0

From http://www.cplusplus.com/reference/string/string/string/.

Use std::String s(data.begin(), data.end());.

a_guest
  • 34,165
  • 12
  • 64
  • 118