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?

1
  • Yes, std::string s(data.begin(), data.end()); Or if you already have a string: s.assign(data.begin(), data.end()); Commented Sep 16, 2015 at 14:54

2 Answers 2

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

Sign up to request clarification or add additional context in comments.

Comments

0

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

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.