如何设置 istream_iterator 不忽略空行
我在 istream_iterator 读取文件时遇到问题,因为它忽略空行,但我需要将这些空行包含为“”。
我应该如何修改下面的程序以获得向量中的 5 行?
#include <sstream>
#include <string>
#include <iostream>
#include <vector>
#include <iterator>
using namespace std;
int main(int argc, const char *argv[])
{
string test = "There\nare\n\nfive\nstrings";
stringstream stream(test);
vector<string> v;
copy(istream_iterator<string>(stream),istream_iterator<string>(),back_inserter(v));
cout << v.size() << endl;
return 0;
}
I'm having problems with istream_iterator reading a file because it ignores blank lines, but I need that those blank lines are included as "".
How should I modify the program below to get the 5 lines in my vector?
#include <sstream>
#include <string>
#include <iostream>
#include <vector>
#include <iterator>
using namespace std;
int main(int argc, const char *argv[])
{
string test = "There\nare\n\nfive\nstrings";
stringstream stream(test);
vector<string> v;
copy(istream_iterator<string>(stream),istream_iterator<string>(),back_inserter(v));
cout << v.size() << endl;
return 0;
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
这里的问题并不是真正的 istream_iterator - 它是流的问题,流被设置为将所有连续的“空白”视为单个分隔符。
正如我在之前的回答中概述的那样,有多种方法可以将 istream_iterator 获取到 逐行阅读。请注意,在另一种情况下,这些的工作方式会有所不同:如果一行中有多个单词,例如:“There are\nfour\n\nstrings”,则这会将“There are”读为单个字符串,其中您的原始版本会将其读取为两个单独的字符串。我不确定在这种情况下你真正想要什么(或者它可能永远不会出现,所以你不在乎)。
The problem here isn't really with
istream_iterator
- it's with streams, which are set up to treat all runs of consecutive "white space" as a single delimiter.As I outlined in a previous answer, there are a number of ways to get
istream_iterator
to read line-by-line though. Note that these will work a bit differently under one other circumstance: if you have more than one word on a line, like: "There are\nfour\n\nstrings", this would read "There are" as a single string, where your original would read it as two separate strings. I'm not sure what you really want in that case though (or maybe it'll never arise, so you don't care).如果换行符是字符串中唯一的分隔符,则可以设置 boost.tokenizer 保留空标记,并用它进行解析:
否则,是的,行输入迭代器和行代理是很好的一般情况解决方案。
If newlines are the only delimiters in your string, you can set up boost.tokenizer to keep empty tokens, and parse with it:
Otherwise, yes, line input iterators and line proxies are great general case solutions.