c++ - 自定义 istream 结束迭代器

标签 c++ c++11

我想从 istream 中读取一行文本并将其拆分成单词。我当前的代码是

vector<string>((istream_iterator<string>(f)),
                                istream_iterator<string>());

其中 f 是一个 ifstream目的。但是,这会读取到文件末尾,我想在它到达换行符时停止读取。有什么办法可以做类似 istream_iterator<string>("\n") 的事情吗?所以 vector 构造函数会在到达换行符时停止向后推?

最佳答案

使用std::getline() 读取一行,然后使用std::istringstream 从该行读取单词,例如:

std::string line;
std::getline(f, line);
std::istringstream iss(line);
std::vector<std::string> words(
    std::istream_iterator<std::string>(iss),
    std::istream_iterator<std::string>()
);

关于c++ - 自定义 istream 结束迭代器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54965470/

相关文章:

c++ - 我可以使用 C/C++ 预处理器添加数字吗?

c++ - 终止 worker

c++ - 测试 boost::mpl::or_ 的计算结果是真还是假

c++ - 将数组的值分配给C++中另一个数组的索引

c++ - 可变数量的(const)引用参数

c++ - "error C2678: binary ' = ' : no operator found which takes a left-hand operand of type..."使用lambda函数进行 map 过滤时

c++ - qt C++信号与槽中删除函数错误的使用

c++ - IDC 是什么意思?

c++ - 当我构建我的项目时,visual studio 2008 没有创建 .exe 文件。任何想法为什么?

c++ - 为什么 using 指令不是 "associate"与普通函数?