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++ 迭代器?


- 将函数的返回值分配给引用 C++? 2022-01-01
- 哪个更快:if (bool) 或 if(int)? 2022-01-01
- 从父 CMakeLists.txt 覆盖 CMake 中的默认选项(...)值 2021-01-01
- OpenGL 对象的 RAII 包装器 2021-01-01
- GDB 不显示函数名 2022-01-01
- 将 hdc 内容复制到位图 2022-09-04
- XML Schema 到 C++ 类 2022-01-01
- 如何提取 __VA_ARGS__? 2022-01-01
- DoEvents 等效于 C++? 2021-01-01
- 使用 __stdcall & 调用 DLLVS2013 中的 GetProcAddress() 2021-01-01