gpt4 book ai didi

c++ - 在 C++ 中获取文本文件的第 n 行

转载 作者:可可西里 更新时间:2023-11-01 18:26:49 26 4
gpt4 key购买 nike

我需要读取文本文件的第 n 行(例如 textfile.findline(0) 会找到加载了 ifstream textfile 的文本文件的第一行) .这可能吗?我不需要将文件的内容放在一个数组/vector 中,我只需要将文本文件的特定行分配给一个变量(特别是一个 int)。

附言我正在寻找不需要我使用任何大型外部库(例如 Boost)的最简单的解决方案提前致谢。

最佳答案

这个怎么样?

std::string ReadNthLine(const std::string& filename, int N)
{
std::ifstream in(filename.c_str());

std::string s;
//for performance
s.reserve(some_reasonable_max_line_length);

//skip N lines
for(int i = 0; i < N; ++i)
std::getline(in, s);

std::getline(in,s);
return s;
}

关于c++ - 在 C++ 中获取文本文件的第 n 行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7273326/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com