Is there a C++ iterator that can iterate over a file line by line?(是否有可以逐行迭代文件的 C++ 迭代器?)
问题描述
我想要一个 istream_iterator 风格的迭代器,它将文件的每一行作为字符串而不是每个单词返回.这可能吗?
I would like to get an istream_iterator-style iterator that returns each line of the file as a string rather than each word. Is this possible?
推荐答案
这个技巧已经被其他人发布了 在上一个线程中.
This same trick was already posted by someone else in a previous thread.
很容易拥有 std::istream_iterator 做你想做的事:
It is easy to have std::istream_iterator do what you want:
namespace detail
{
class Line : std::string
{
friend std::istream & operator>>(std::istream & is, Line & line)
{
return std::getline(is, line);
}
};
}
template<class OutIt>
void read_lines(std::istream& is, OutIt dest)
{
typedef std::istream_iterator<detail::Line> InIt;
std::copy(InIt(is), InIt(), dest);
}
int main()
{
std::vector<std::string> v;
read_lines(std::cin, std::back_inserter(v));
return 0;
}
这篇关于是否有可以逐行迭代文件的 C++ 迭代器?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:是否有可以逐行迭代文件的 C++ 迭代器?
基础教程推荐
- 如何部分禁用 cmake C/C++ 自定义编译器检查 2021-01-01
- 如何在 C++ 中正确使用命名空间? 2022-01-01
- 提升 ASIO 流缓冲 2021-01-01
- C++:获取传递给函数的多维数组的行大小 2021-01-01
- 为什么我们不能使用“虚拟继承"?在 COM 中? 2022-01-01
- c++ STL设置差异 2022-01-01
- 随机插入/删除的综合向量与链表基准 2022-01-01
- 如何更改 SysDateTimePick32 或 CDateTimeCtrl 的背景颜色? 2022-01-01
- 与 CAS 的原子交换(使用 gcc 同步内置函数) 2022-01-01
- 将不可复制的闭包对象传递给 std::function 参数 2021-01-01
