簡體   English   中英

getline()讀取額外的一行

[英]getline() reads an extra line

ifstream file("file.txt");
 if(file.fail())
{
cout<<"Could not open the file";
exit(1);
}
else
{
      while(file)
      {
        file.getline(line[l],80); 
                          cout<<line[l++]<<"\n";
      } 
}

我正在使用二維字符數組來保持從文件中讀取文本(多於一行)以計算文件中的行數和單詞數,但是問題是getline總是讀取額外的一行。

您在編寫此代碼時的代碼:

ifstream file("file.txt");
 if(file.fail())
{
cout<<"Could not open the file";
exit(1);
}
else
{
      while(file)
      {
        file.getline(line[l],80); 
        cout<<line[l++]<<"\n";
      } 
}

第一次getline失敗時,您仍然會增加行計數器並輸出(不存在)行。

始終檢查錯誤。

額外建議:使用<string>標頭中的std::string ,並使用其getline函數。

干杯和健康。

僅當file.good()為true時才執行cout 您看到的額外行來自對file.getline()的最后一次調用,該調用讀取了文件末尾的內容。

問題是,當你在文件上的測試結束file仍然會成功,因為你還沒有讀取文件的末尾。 因此,您還需要測試getline()的返回值。

由於您需要測試getline()的返回值是否成功,因此您最好將它放在while循環中:

while (file.getline(line[l], 80))
    cout << line[l++] << "\n";

這樣,您就不需要對filegetline()進行單獨的測試。

這將解決您的問題:

ifstream file("file.txt");
if(!file.good())
{
  cout<<"Could not open the file";
  exit(1);
}
else
{
  while(file)
  {
    file.getline(line[l],80);
       if(!file.eof())
          cout<<line[l++]<<"\n";
  } 
}

它更強大

文件是否以換行符結尾? 如果確實如此,則只有經過一個額外的循環后,才會觸發EOF標志。 例如,如果文件是

abc\n
def\n

然后循環將運行3次,第一次將獲得abc ,第二次將獲得def ,第三次將什么也沒有。 這可能就是為什么您看到另外一行。

嘗試在getline之后檢查流上的故障位。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM