Есть ли итератор C++, который может перебирать файл строка за строкой?
Я хотел бы получить итератор в стиле istream_iterator, который возвращает каждую строку файла в виде строки, а не каждое слово. Это возможно?
8 ответов
РЕДАКТИРОВАТЬ: этот же трюк уже был опубликован кем-то в предыдущей теме.
Это легко иметь std::istream_iterator
делай что хочешь:
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;
}
Стандартная библиотека не предоставляет итераторов для этого (хотя вы можете реализовать что-то подобное самостоятельно), но вы можете просто использовать функцию getline (не метод istream) для чтения всей строки из входного потока в строку C++,
Пример:
#include <iostream>
#include <fstream>
#include <string>
#include <algorithm>
using namespace std;
int main()
{
ifstream is("test.txt");
string str;
while(getline(is, str))
{
cout<<str<<endl;
}
return 0;
}
Вот решение. В примере напечатайте входной файл с @@ в конце каждой строки.
#include <iostream>
#include <iterator>
#include <fstream>
#include <string>
using namespace std;
class line : public string {};
std::istream &operator>>(std::istream &is, line &l)
{
std::getline(is, l);
return is;
}
int main()
{
std::ifstream inputFile("input.txt");
istream_iterator<line> begin(inputFile);
istream_iterator<line> end;
for(istream_iterator<line> it = begin; it != end; ++it)
{
cout << *it << "@@\n";
}
getchar();
}
Изменить: Мануэль был быстрее.
Вы можете написать свой собственный итератор. Это не так сложно. Итератор - это просто класс, в котором (проще говоря) определены операторы приращения и *.
Посмотрите на http://www.drdobbs.com/cpp/184401417 чтобы начать писать свои собственные итераторы.
Также можно использовать цикл for на основе диапазона :
// Read from file.
std::ifstream f("test.txt");
for (auto& line : lines(f))
std::cout << "=> " << line << std::endl;
// Read from string.
std::stringstream s("line1\nline2\nline3\n\n\nline4\n\n\n");
for (auto& line : lines(s))
std::cout << "=> " << line << std::endl;
куда
lines
определяется следующим образом:
#include <string>
#include <iterator>
#include <istream>
struct line_iterator {
using iterator_category = std::input_iterator_tag;
using value_type = std::string;
using difference_type = std::ptrdiff_t;
using reference = const value_type&;
using pointer = const value_type*;
line_iterator(): input_(nullptr) {}
line_iterator(std::istream& input): input_(&input) { ++*this; }
reference operator*() const { return s_; }
pointer operator->() const { return &**this; }
line_iterator& operator++() {
if (!std::getline(*input_, s_)) input_ = nullptr;
return *this;
}
line_iterator operator++(int) {
auto copy(*this);
++*this;
return copy;
}
friend bool operator==(const line_iterator& x, const line_iterator& y) {
return x.input_ == y.input_;
}
friend bool operator!=(const line_iterator& x, const line_iterator& y) {
return !(x == y);
}
private:
std::istream* input_;
std::string s_;
};
struct lines {
lines(std::istream& input): input_(input) {}
line_iterator begin() const { return line_iterator(input_); }
line_iterator end() const { return line_iterator(); }
private:
std::istream& input_;
};
Вы можете использовать istreambuf_iterator вместо istream_iterator. Он не игнорирует управляющие символы, такие как istream_iterator.
code.cpp:
#include <iterator>
#include <iostream>
#include <fstream>
using namespace std;
int main()
{
ifstream file("input.txt");
istreambuf_iterator<char> i_file(file);
istreambuf_iterator<char> eof;
std::string buffer;
while(i_file != eof)
{
buffer += *i_file;
if(*i_file == '\n')
{
std::cout << buffer;
buffer.clear();
}
++i_file;
}
return 0;
}
input.txt:
ahhhh test *<-- There is a line feed here*
bhhhh second test *<-- There is a line feed here*
выход:
ahhhh test
bhhhh second test
Вот довольно чистый подход, использующий boost:: tokenizer. Это возвращает объект, предоставляющийbegin()
а также end()
функции-члены; полный интерфейс см. в документации tokenizer
класс.
#include <boost/tokenizer.hpp>
#include <iostream>
#include <iterator>
using istream_tokenizer = boost::tokenizer<boost::char_separator<char>,
std::istreambuf_iterator<char>>;
istream_tokenizer line_range(std::istream& is);
{
using separator = boost::char_separator<char>;
return istream_tokenizer{std::istreambuf_iterator<char>{is},
std::istreambuf_iterator<char>{},
separator{"\n", "", boost::keep_empty_tokens}};
}
Это жесткие коды char
как тип символа потока, но это можно сделать по шаблону.
Функцию можно использовать следующим образом:
#include <sstream>
std::istringstream is{"A\nBB\n\nCCC"};
auto lines = line_range(is);
std::vector<std::string> line_vec{lines.begin(), lines.end()};
assert(line_vec == (std::vector<std::string>{{"A", "BB", "", "CCC"}}));
Естественно, его также можно использовать с std::ifstream
создается при открытии файла:
std::ifstream ifs{"filename.txt"};
auto lines = line_range(ifs);
Джерри Коффин в приведенном выше сообщении " Итерация за кадром за строкой за строкой" описал "еще одну возможность (которая) использует часть стандартной библиотеки, о которой большинство людей даже не подозревают". Следующее применяет этот метод (который я искал) для решения проблемы итерации по файлу строка за строкой, как было запрошено в текущем потоке.
Сначала фрагмент, скопированный непосредственно из ответа Джерри в соответствующей теме:
struct line_reader: std::ctype<char> {
line_reader(): std::ctype<char>(get_table()) {}
static std::ctype_base::mask const* get_table() {
static std::vector<std::ctype_base::mask> rc(table_size, std::ctype_base::mask());
rc['\n'] = std::ctype_base::space;
return &rc[0];
}};
А теперь добавьте в ifstream пользовательский языковой стандарт, описанный Джерри, и скопируйте его из infstream в ofstream.
ifstream is {"fox.txt"};
is.imbue(locale(locale(), new line_reader()));
istream_iterator<string> ii {is};
istream_iterator<string> eos {};
ofstream os {"out.txt"};
ostream_iterator<string> oi {os,"\n"};
vector<string> lines {ii,eos};
copy(lines.begin(), lines.end(), oi);
Выходной файл ("out.txt") будет точно таким же, как и входной файл ("fox.txt").