c++ - 如何从具有 null(0) 字符的 char 数组创建 C++ istringstream?

标签 c++ istream arrays null-character

我有一个 char 数组,它在随机位置包含空字符。我尝试使用这个数组 (encodedData_arr) 创建一个 iStringStream,如下所示,

我使用此 iStringStream 将二进制数据(Iplimage 的图像数据)插入 MySQL 数据库 blob 字段(使用 MySQL Connector/C++ 的 setBlob(istream *is) ),它只存储第一个空字符之前的字符。

有没有办法使用带有空字符的 char 数组创建 iStringStream?

unsigned char *encodedData_arr = new unsigned char[data_vector_uchar->size()];
// Assign the data of vector<unsigned char> to the encodedData_arr
for (int i = 0; i < vec_size; ++i)
{
 cout<< data_vector_uchar->at(i)<< " : "<< encodedData_arr[i]<<endl;
}

// Here the content of the encodedData_arr is same as the data_vector_uchar
// So char array is initializing fine.
istream *is = new istringstream((char*)encodedData_arr, istringstream::in || istringstream::binary);

prepStmt_insertImage->setBlob(1, is);
// Here only part of the data is stored in the database blob field (Upto the first null character)

最佳答案

字符串中的空字符没有什么特别之处

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

当然可以

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

它会将其解释为转换为 std::string 的 C 风格字符串,因此会在 \0 处停止,而不将其视为真正的内容字节。明确告诉 std::string 大小允许它使用任何空字节作为实际内容数据。

如果想直接从char数组中读取,可以使用strstream

std::istrstream iss(data, N);

这将直接从 data 提供的数据中读取,最多 N 字节。 strstream 已正式宣布“弃用”,但它仍将在 C++0x 中,因此您可以使用它。或者你创建自己的 streambuf,如果你真的需要像那样从原始 char* 中读取。

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)
  { }
};

关于c++ - 如何从具有 null(0) 字符的 char 数组创建 C++ istringstream?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2786816/

相关文章:

java - 我如何使用此代码更改为没有任何数组?

使用 getter 和 setter 存储全局 std::string 标签的 C++ 策略

c++ - 在 C++ 中向上转型和向下转型跳过层次结构?

c++ - 不明白 cplusplus.com 的 istream::read 示例

c++ - 如何将 QByteArray 转换为 std::istream 或 std::ifstream?

javascript - 根据对象的另一个值将相同的多个对象插入多个数组

jquery - 从 ajax JSON 响应构建数组

c++ - 对用户定义函数的 undefined reference

c++ - 在这个例子中如何避免代码重复?

c++ - 如何使 std::istream_iterator 只读到行尾?