有一个txt文档 里面有多行数据
怎么获取指定行的内容 函数带一个int参数 取第几行的内容
如readtxtline(int line)
#include <iostream>
#include <fstream>
#include <string>
#include <vector>
#include <optional>
#include <numeric>
class FileReader {
constexpr static size_t read_current = std::numeric_limits<size_t>::max();
public:
FileReader(std::string filename)
: line_no_{ 0 },
filename_{ std::move(filename) },
stream_{ filename_ },
positions_{ stream_.tellg() } {}
~FileReader() { stream_.close(); }
std::optional<std::string> read_line(size_t index = read_current) {
if (index == read_current) {
return _read_forward();
}
else {
if (_seek_line(index)) {
return _read_forward();
}
else {
return std::nullopt;
}
}
}
std::optional<std::string> _read_forward() {
std::string res;
if (std::getline(stream_, res)) {
++line_no_;
if (positions_.size() <= line_no_)
positions_.push_back(stream_.tellg());
return res;
}
else {
_seek_line(line_no_);
stream_.clear(std::ios_base::eofbit);
return std::nullopt;
}
}
bool _seek_line(size_t i) {
if (i < positions_.size()) {
line_no_ = i;
stream_.seekg(positions_[i]);
return true;
}
else {
_seek_line(positions_.size() - 1);
while (_read_forward() && line_no_ < i)
;
return i == line_no_;
}
}
public:
size_t line_no_;
std::string filename_;
std::ifstream stream_;
std::vector<std::streampos> positions_;
};
int main() {
FileReader reader(R"(test.txt)");
for (auto i : { 0, 1, 3, 2, 7, 14, 12, 486, 487, 488, 489, 1 }) {
auto line = reader.read_line(i);
std::cout << i << ' ' << (line ? line.value() : std::string{ "read to end" }) << '\n';
}
}
3 回答2.1k 阅读✓ 已解决
2 回答3.9k 阅读✓ 已解决
3 回答3.5k 阅读
3 回答534 阅读✓ 已解决
1 回答3.3k 阅读
1 回答1.1k 阅读✓ 已解决
1 回答2.1k 阅读