我需要读取文本文件的第 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/