0
我已經得到了下面的代碼,我試圖計算輸入文件中的行數,並且嘗試了幾種不同的方式來實現它,但沒有運氣。什麼是計算文本文件中行數的最佳條件?
int checkData(string File)
{
string temp;
int linecount = 0;
ifstream input(File);
input.open(File);
while()
{
getline(input,temp);
linecount++;
temp.clear();
}
return linecount;
}
到目前爲止,我已經試過:
while(!input.eof())
{
...
}
和
while(getline(input,temp).good())
{
...
}
第一個犯規打破循環,我不明白爲什麼。 (我相當肯定)getline有一個內置的流緩衝區,所以每次我拉一條線並將它扔出去時,它都會自動讀取網絡線,但是沒有骰子。對於第二個,循環根本不執行,這對我來說仍然沒有意義(這表示文件的第一行不是很好的輸入?)。 我使用的測試文件是:
this is a test this Cake
this is a test this Cake
this is a test this Cake
this is a test this Cake
所以linecount要正確執行時會傳回4。在執行此操作之前,我已經檢查過以確保文件正確打開。
第一個是衆所周知的問題。從第二個移除'.good()'應該解決它。 – Incomputable
剛剛運行過,並且在刪除.good()標誌時它仍然不執行while循環。 –
@GrahamWilson你應該仔細檢查 - 刪除好()應該確實解決你的問題(不只是原則上;我複製和編譯你的代碼)。順便說一句,temp.clear()是沒有必要的。 – jwimberley