Would something like this be “right” for you?
#include <algorithm>
#include <iostream>
#include <vector>
#include <iterator>
int main()
{
const unsigned char buf[] = {'A', 'B', '\0', '\0', 'C', 'd', 'e', 'f'};
const std::vector<int> data(buf, buf + sizeof buf/sizeof 0[buf]);
std::copy(data.begin(), data.end(),
std::ostream_iterator<int>(std::cout, " "));
return 0;
}
Result:
65 66 0 0 67 100 101 102
Of course, it doesn’t matter that this vector is bound to stringstream, and then from to to int, but it will overflow very quickly:
#include <algorithm>
#include <iostream>
#include <sstream>
#include <string>
#include <vector>
struct PutElementToStream
{
PutElementToStream(std::stringstream &stream)
: stream_(stream)
{}
void operator()(int value)
{
stream_ << value;
}
private:
std::stringstream &stream_;
};
int main()
{
const unsigned char buf[] = {'A', 'B', '\0', '\0', 'C', 'd', 'e', 'f'};
const std::vector<int> data(buf, buf + sizeof buf/sizeof 0[buf]);
std::stringstream stream;
std::for_each(data.begin(), data.end(), PutElementToStream(stream));
std::cout << "stream: " << stream.str() << "\n";
int value = 0;
stream >> value;
std::cout << "int value: " << value << "\n";
const std::string string_value(stream.str());
std::cout << "string value: " << string_value << "\n";
return 0;
}
Result:
stream: 65660067100101102
int value: 0
string value: 65660067100101102
source
share