开发者

Help in managing a iostream

Suppose that I get a stringbuf with some content that include certain character sequences who must be removed:

std::stringbuf string_buff;
std::iostream io_stream (&string_buff);
io_stream << "part-one\r\npart-two\r\npart-three\r\nEND";

There, the CRLF pairs must be removed, so I've tested some as:

int pos = 0;
while (true) {
    pos = string_buff.str().rfind("\r\n");
    if (pos == string_buff.str().npos) {
        break;
    } else {
        std::string preamble = string_buff.str().substr(0, pos);
        std::string postamble = string_buff.str().substr(pos +2);
        io_stream.seekp(0);
        io_stream << preamble << postamble;
    }
}

But the sequence remains of the same length. So, I get the following result:

 part-onepart-twopart-threeENDNDNDND

I suppose that there are some way to do this -and more elegant- but I'm unable to find the way.

By the way. It seems that the direct manipulation on the inner string does not work. I say tings like:

 string_buff.str().clear();

Neither

 io_stream.clear();

or

 io_stream.flush();

Unfortunately I mistaken in my initial approach

As I mentioned earlier, the real problem is related to a boost::asio::stream开发者_运维百科buf and my mistake was in try to mimic that, with a std::istream in a separate console application for test purposes.

Of course, with an asio::streambuf y can't do some as

 strembuf.str("");

So the real situation is this:

 boost::asio::streambuf stream_buff;
 std::iostream response_stream(&stream_buff);
 response_stream << "part-one\r\npart-two\r\npart-three\r\nEND";

My apologies for the confussion.

The question remains the same: How can I remove the CRLF -or any other- character sequence from the input?


You are close! The way to make the streambuf empty is

String_buff.str("");

That will assign it the empty string.

(string_buff.str().clear() just empties a copy of the contents :-)


Use Boost.String.

string s(string_buf.str());
boost::erase_all(s, "\r\n");
string_buf.str(s);

or, if you need the line-ends replaced with other whitespace:

string s(string_buf.str());
boost::replace_all(s, "\r\n", " ");
string_buf.str(s);

And yes, stringbuf.str() returns a copy of, not a reference to the string.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜