[英]Reading a file and counting the number of lines c++
您好,我正在努力讀取文件並計算其中的行數。 我傳遞了這段代碼,我得到的代碼比我的文件多了 1 行。
` ifstream fin;
fin.open("car.txt");
// num of cars counted
numberOffCars = 0;
while (fin.good()) //while i have not reached the eof
{
getline(fin, line);
numberOffCars++;
}
cout<<numberOffCars<<endl;
fin.close();``
謝謝
您可以通過簡單地使用string::empty()
來檢查行是否為空。 在這里,我使用std::ws
來提取前導空格(如果有的話)。
代碼:
#include <iostream>
#include <istream>
#include <fstream>
#include <string>
int main() {
std::ifstream fin("car.txt");
if (not fin) {
std::cerr << "car.txt not found in working directory!";
return -1;
}
std::string str;
int n = 0;
while (fin >> std::ws and std::getline(fin, str))
if(not str.empty())
++n;
std::cout << n;
}
這將忽略空行(只有空格的行)。 此外,您的代碼的主要問題是您在即將到達EOF
時使用getline
。 您需要在讀取輸入后檢查條件。
在這里,在我的代碼中,將首先評估getline
然后檢查fin
(由getline
返回); 它會告訴我們上次操作是成功還是失敗。 如果達到EOF
,它將失敗,因此while
循環將終止。
有關詳細信息,請參閱此線程: Why is iostream::eof
inside a loop condition (ie while (.stream.eof())
) considered wrong? 我想引用其中的一條評論: Just because we haven't reached the EOF, doesn't mean the next read will success 。
這是因為您的代碼在讀取“EOF”和 numberOffCars++ 后知道“EOF”; 所以 numberOffCars 的結果比你預期的多 1。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.