c++ - 字符串迭代器与读取每一行不兼容

标签 c++ string boost assert boost-tokenizer

我有一个 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 上读到了这个错误,但我很难找到我的错误。

有人可以帮帮我吗?

非常感谢,

最好的问候,

尼克修斯

最佳答案

为了效率/错误报告,我喜欢让它成为不可复制的:

查看 Live on 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:

查看 Live on 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";
    };
}

关于c++ - 字符串迭代器与读取每一行不兼容,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20338247/

相关文章:

C++ Boost asio 获取数据大小?

c++ - 使用C++在二叉树中添加非递归函数

c++ - BOOST_PP_SEQ_SIZE 如何工作?

c++ - boost::spirit 递归命令式 c++ 语法:BOOST_FUSION_ADAPT_STRUCT 失败

c++ - 我可以使用 boost bind 定义用于对 STL 列表进行排序的比较器吗?

c++ - Boost Asio - 服务器没有收到消息

c++ - 我如何按值跨文件传递结构

C++ 编译器选择了错误的命名空间

c++ - isalpha 总是返回 0

c - 在C中手动将4位int(十进制)提取到字符串中