簡體   English   中英

使用getline從文件中讀取多行?

[英]reading multiple lines from a file using getline?

我正在嘗試讀取names.txt文件中的數據,並輸出每個人的全名和理想體重。 使用循環從文件中讀取每個人的姓名以及腳和英寸。 該文件顯示為:

Tom Atto 6 3 Eaton Wright 5 5 Cary Oki 5 11 Omar Ahmed 5 9

我為此使用以下代碼:

string name;
int feet, extraInches, idealWeight;
ifstream inFile;

inFile.open ("names.txt");

while (getline(inFile,name))
{
    inFile >> feet;
    inFile >> extraInches;

    idealWeight = 110 + ((feet - 5) * 12 + extraInches) * 5;

    cout << "The ideal weight for " << name << " is " << idealWeight << "\n";

}
inFile.close();

當我運行此即時消息獲取輸出時:

The ideal weight for Tom Atto is 185 The ideal weight for is -175

讀取兩個extraInches值后,在while循環中添加此語句。

inFile.ignore(std::numeric_limits<std::streamsize>::max(), '\n');

它會忽略您在while循環中讀取的第二個整數之后的'\\n' 您可能會引用: 讀取文件C ++時使用getline和>>

您遇到了問題,因為下線之后

inFile >> extraInches;

在循環的第一次迭代中執行,流中仍然存在換行符。 下次調用getline只會返回一個空行。 后續通話

inFile >> feet;

失敗,但您不檢查呼叫是否成功。

我想談談與您的問題有關的幾件事。

  1. 使用getline混合未格式化的輸入和使用operator>>混合格式化的輸入充滿了問題。 躲開它。

  2. 要診斷與IO相關的問題,請始終在操作后檢查流的狀態。

對於您的情況,可以使用getline讀取文本行,然后使用istringstream從這些行中提取數字。

while (getline(inFile,name))
{
   std::string line;

   // Read a line of text to extract the feet
   if ( !(inFile >> line ) )
   {
      // Problem
      break;
   }
   else
   {
      std::istringstream str(line);
      if ( !(str >> feet) )
      {
         // Problem
         break;
      }
   }

   // Read a line of text to extract the inches
   if ( !(inFile >> line ) )
   {
      // Problem
      break;
   }
   else
   {
      std::istringstream str(line);
      if ( !(str >> inches) )
      {
         // Problem
         break;
      }
   }

    idealWeight = 110 + ((feet - 5) * 12 + extraInches) * 5;

    cout << "The ideal weight for " << name << " is " << idealWeight << "\n";

}

暫無
暫無

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

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