1

我有一个 std::ostringstream。我想迭代这个 std::ostringstream 的每一行。

我使用 boost::tokenizer :

std::ostringstream HtmlStream;
.............
typedef boost::tokenizer<boost::char_separator<char> > line_tokenizer;
line_tokenizer tok(HtmlStream.str(), boost::char_separator<char>("\n\r"));

for (line_tokenizer::const_iterator i = tok.begin(), end = tok.end(); i != end; ++i)
{
    std::string str = *i;
}

在线上

for (line_tokenizer::const_iterator i = tok.begin(), end = tok.end(); i != end; 

我有一个“字符串迭代器不兼容”的断言错误。我已经在谷歌和 StackOverflow 上阅读过这个错误,但我很难找到我的错误。

任何人都可以帮助我吗?

非常感谢,

此致,

尼克修斯

4

1 回答 1

2

我喜欢让它不复制以提高效率/错误报告:

在 Coliru 上看到它

#include <boost/algorithm/string/split.hpp>
#include <boost/algorithm/string/classification.hpp>
#include <iostream>
#include <vector>

int main()
{
    auto const& s = "hello\r\nworld";

    std::vector<boost::iterator_range<char const*>> lines;
    boost::split(lines, s, boost::is_any_of("\r\n"), boost::token_compress_on);

    for (auto const& range : lines)
    {
        std::cout << "at " << (range.begin() - s) << ": '" << range  << "'\n";
    };
}

印刷:

at 0: 'hello'
at 7: 'world'

这比所示的大多数替代方案更有效。当然,如果你需要更多的解析能力,可以考虑 Boost Spirit:

在 Coliru 上看到它

#include <boost/spirit/include/qi.hpp>

int main()
{
    std::string const s = "hello\r\nworld";

    std::vector<std::string> lines;

    {
        using namespace boost::spirit::qi;
        auto f(std::begin(s)), 
             l(std::end(s));
        bool ok = parse(f, l, *(char_-eol) % eol, lines);
    }

    for (auto const& range : lines)
    {
        std::cout << "'" << range  << "'\n";
    };
}
于 2013-12-02T23:06:05.263 回答