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++ 迭代器?
基础教程推荐
- 为什么 typeid.name() 使用 GCC 返回奇怪的字符以及如 2022-09-16
- 如果我为无符号变量分配负值会发生什么? 2022-01-01
- 通过引用传递 C++ 迭代器有什么问题? 2022-01-01
- CString 到 char* 2021-01-01
- 为什么派生模板类不能访问基模板类的标识符? 2021-01-01
- GDB 显示调用堆栈上函数地址的当前编译二进制文 2022-09-05
- 非静态 const 成员,不能使用默认赋值运算符 2022-10-09
- 我应该对 C++ 中的成员变量和函数参数使用相同的名称吗? 2021-01-01
- 为什么 RegOpenKeyEx() 在 Vista 64 位上返回错误代码 2021-01-01
- 初始化列表*参数*评估顺序 2021-01-01
