在C ++中获取文本文件的第n行 [英] Getting the nth line of a text file in C++
本文介绍了在C ++中获取文本文件的第n行的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我需要读取文本文件的第n行(例如 textfile.findline(0)
)将找到加载了<$ c $的文本文件的第一行c> ifstream textfile )。这可能吗?
我不需要把文件的内容放在一个数组/向量中,我只需要将一个特定的文本文件行分配给一个变量(特别是一个int)。
PS我正在寻找最简单的解决方案,不需要我使用任何大型的外部库(例如Boost)
在此先感谢。
解决方案 ($)$ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $'
{
std :: ifstream in(filename.c_str());
std :: string s;
//表现
s.reserve(some_reasonable_max_line_length);
//跳过N行
for(int i = 0; i< N; ++ i)
std :: getline(in,s);
std :: getline(in,s);
return s;
}
{
std :: ifstream in(filename.c_str());
std :: string s;
//表现
s.reserve(some_reasonable_max_line_length);
//跳过N行
for(int i = 0; i< N; ++ i)
std :: getline(in,s);
std :: getline(in,s);
return s;
}
I need to read the nth line of a text file (e.g. textfile.findline(0)
would find the first line of the text file loaded with ifstream textfile
). Is this possible?
I don't need to put the contents of the file in an array/vector, I need to just assign a specific line of the text file to a varible (specifically a int).
P.S. I am looking for the simplest solution that would not require me to use any big external library (e.g. Boost) Thanks in advance.
解决方案
How about this?
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 ++中获取文本文件的第n行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文