[英]How to ignore a line in ifstream in C++?
我想用 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
和operator>>
解析文本行。 還有許多其他技術可以解析字符串。
#include <algorithm>
.
.
.
word.erase(remove(word.begin(), word.end(), '/'), word.end());
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.