2015-03-31 189 views
0

這是我的程序。它應該從輸入文件讀取每行並以整潔的格式顯示在控制檯上。但是,getline只讀取第一行。getline函數只讀取第一行

#include <iostream> 
#include <fstream> 
#include <string> 
#include <iomanip> 
#include <sstream> 
using namespace std; 

int main(int argc, char *argv[]){ 
    ifstream inFile; 
    string state, quantityPurchased, pricePerItem, itemName;  
    inFile.open("lab11.txt"); 
    if (inFile.fail()){ 
     perror ("Unable to open input file for reading"); 
     return 1; 
    } 
    string line; 
    istringstream buffer; 
    while(getline(inFile, line)){ 
     buffer.str(line); 
     buffer >> state >> quantityPurchased >> pricePerItem >> itemName; 

     cout << left << setw(2) << state << " "; 
     cout << setw(15) << itemName << " "; 
     cout << right << setw(3) << quantityPurchased << " "; 
     cout << setw(6) << pricePerItem << endl; 
    } 
} 

輸入文件看起來是這樣的:

TX 15 1.12 Tissue 
TX 1 7.82 Medication 
TX 5 13.15 Razors 
WY 2 1.13 Food 
WY 3 3.71 Dinnerware 

但它顯示,因爲這(正在舉辦前):

TX 15 1.12 Tissue 
TX 15 1.12 Tissue 
TX 15 1.12 Tissue 
TX 15 1.12 Tissue 
TX 15 1.12 Tissue 

回答

2

緩衝區發生故障的第二循環後提取,因爲你還沒有清除狀態位。這樣做:

buffer.clear() 
buffer.str(line); 

您可以通過添加一些輸出到你的代碼中看到這一點:第一次通過你的循環後

std::cout << "EOF: " << buffer.eof() << std::endl; 

,與流到達輸入字符串和EOF結束位將被設置。在下一個循環開始時重置字符串不會重置該位,因此它仍將被設置。當您嘗試第二次提取時,流認爲它已經在文件的末尾,並且認爲它沒有任何可讀的內容,因此它會提前出局。清除狀態位修復了這一點。

+0

哦,非常感謝。 – 2015-03-31 21:04:48