我有一个 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 上读到了这个错误,但我很难找到我的错误。
有人可以帮帮我吗?
非常感谢,
最好的问候,
尼克修斯
最佳答案
为了效率/错误报告,我喜欢让它成为不可复制的:
#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:
#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/