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++ 迭代器?
基础教程推荐
- 我有静态或动态 boost 库吗? 2021-01-01
- 静态库、静态链接动态库和动态链接动态库的 .lib 文件里面是什么? 2021-01-01
- 如何检查GTK+3.0中的小部件类型? 2022-11-30
- 这个宏可以转换成函数吗? 2022-01-01
- 如何在 C++ 中初始化静态常量成员? 2022-01-01
- 常量变量在标题中不起作用 2021-01-01
- C++结构和函数声明。为什么它不能编译? 2022-11-07
- 在 C++ 中计算滚动/移动平均值 2021-01-01
- 如何将 std::pair 的排序 std::list 转换为 std::map 2022-01-01
- 如何通过C程序打开命令提示符Cmd 2022-12-09
