c++ - 如何在 C++ 中忽略 ifstream 中的一行?
问题描述
我想用 C++ 读取一个文本文件,我已经使用 ifstream 完成了它。文件:
// The range of 'horizontal' indices, inclusive
// E.g. if the range is 0-4, then the indices are 0, 1, 2, 3, 4
GridX_IdxRange=0-8
// The range of 'vertical' indices, inclusive
// E.g. if the range is 0-3, then the indices are 0, 1, 2, 3
GridY_IdxRange=0-8
// [x,y] grid-areas which are occupied by cities
citylocation.txt
// "next day" forecasted cloud coverage (%) for
// each [x,y] grid-area
cloudcover.txt
// "next day" forecasted atmospheric pressure intensity (%) for
// each [x,y] grid-area
pressure.txt
为此,我编写了以下代码:
// open the file
ifstream fileio;
fileio.open(filename);
// check if file exists
if (!fileio.is_open()) {
cout << "File does not exist";
exit(EXIT_FAILURE);
return -1;
}
// read file
string word;
fileio >> word;
while(fileio.good()) {
fileio.ignore(100, '\n');
cout << word << " ";
fileio >> word;
}
// close file
fileio.close();
我得到以下输出:
// // GridX_IdxRange=0-8 // // GridY_IdxRange=0-8 // citylocation.txt // // cloudcover.txt // // pressure.txt
如何以忽略空行和带有注释的行的方式读取文件?只显示重要信息?
解决方案
这是一种如何忽略的方法:
// read file
string word;
while(std::getline(fileio, word))
{
if (word.find("//") == 0)
{
continue;
}
cout << word << " ";
}
在上述版本中,如果读取的文本在文本开头包含“//”,则循环继续。文本行因此被忽略。
这个想法是在使用之前比较(验证)文本行。例如,要跳过空行,您可以添加一个if
语句来检查空字符串。
我还更改了while
使用适当的模式从文件中读取。
您可以使用std::istringstream
and解析文本行operator>>
。解析字符串还有许多其他技术。