How to create C++ istringstream from a char array with null(0) characters?

做~自己de王妃 提交于 2019-12-04 11:27:20

There is nothing special about null characters in strings

std::istringstream iss(std::string(data, N));
setBlob(&iss);

Of course if you do

std::istringstream iss("haha a null: \0");

It will interpret that as a C-style string converted to std::string, and thus will stop at the \0, not taking it as a real content byte. Telling std::string the size explicitly allows it to consume any null byte as real content data.

If you want to read directly from a char array, you can use strstream

std::istrstream iss(data, N);

That will directly read from the data provided by data, up to N bytes. strstream is declared "deprecated" officially, but it's still going to be in C++0x, so you can use it. Or you create your own streambuf, if you really need to read from a raw char* like that.

struct myrawr : std::streambuf {
  myrawr(char const *s, size_t n) { 
    setg(const_cast<char*>(s), 
         const_cast<char*>(s), 
         const_cast<char*>(s + n));
  }
};

struct hasb { 
  hasb(char const *s, size_t n)
   :m(s, n)
  { }
  myrawr m;
};

// using base-from-member idiom
struct myrawrs : private hasb, std::istream {
  myrawrs(char const *s, size_t n)
    :hasb(s, n), 
     std::istream(&static_cast<hasb*>(this)->m)
  { }
};

// Here only part of the data is stored in the database blob field (Upto the first null character)

How are you checking this? If you are just dumping it to cout, its probably stopping at the first nul. You will need to print character by character.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!