简体   繁体   English

为什么stringstream :: str()截断字符串?

[英]Why stringstream::str() truncates string?

I have stringstream object. 我有stringstream对象。 It is filled through 它通过

stringstream ss;
boost::iostreams::copy(inp,ss);

from

boost::iostreams::filtering_streambuf<boost::iostreams::input> inp;

and actually holds ungzipped file within. 并实际上保存未压缩的文件。

Now if i flush stringstream content to file with 现在如果我将stringstream内容冲洗到文件中

std::ofstream ofs(path_to_file,std::ios_base::out|std::ios_base::binary);
ofs << ss.rdbuf();

everything is ok. 一切都好。 File is filled with complete correct data. 文件中填充了完整正确的数据。

But if i instead of flushing to file construct string like this 但是如果我不是像这样冲洗文件构造字符串

std::string s = ss.str();

content is truncated somewhere in the middle. 内容在中间某处被截断。 It is not a persistent error, and it obviously depends on content of string buffer. 这不是一个持久错误,并且显然取决于字符串缓冲区的内容。

The content is HTML file in several languages. 内容是几种语言的HTML文件。

What can it be? 会是什么 Thanks. 谢谢。

How are you determining that the content is truncated? 您如何确定内容被截断? A stringstream can contain null characters and std::string s = ss.str() will copy those null characters and the characters after it to the std::string object. stringstream可以包含空字符和std::string s = ss.str()后,那些空字符和字符将复制到std::string对象。

However, if you then use functions that treat the std::string object's contents as a C style string, it will appear truncated: 但是,如果您随后使用将std::string对象的内容视为C样式字符串的函数,它将被截断:

#include <sstream>
#include <string>
#include <iostream>
#include <ostream>
#include <string.h>

using namespace std;

stringstream ss;

int main()
{
    ss << 'a' << 'b' << 'c' << (char) '\0' << '1' << '2' << '3';

    string s = ss.str();

    cout << s.size() << endl;
    cout << s.c_str() << " C string length: " << strlen(s.c_str()) << endl;
    cout << s << endl;
}

produces the following output: 产生以下输出:

7
abc C string length: 3
abc 123

It seems like you have null character symbol '\\0' in your file. 您的文件中似乎有空字符符号“ \\ 0”。 That considered as end of string. 那被认为是字符串的结尾。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM