2014-04-23 21 views
0

我是一個初學C++用戶,我曾嘗試與我的同學們合作,但我們一直未能找到這個問題的答案。我們的教師爲我們提供了一個鏈接器,它爲我們運行主要功能,並提供一個簡單的文本文件供我們讀取,目前第二個const char *在標題中是不重要的,因爲現在我需要的是從文件const char * saifFile中讀取數據並將其顯示在屏幕上。當我運行我的程序時,我發現它會提前停止閱讀。而且我知道你可能無法提供幫助,因爲你無法訪問鏈接器,但任何幫助都將不勝感激。我想知道爲什麼我的閱讀文件提前停止

這裏是我的所有代碼:

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

const int DESC_SIZE = 37; 

struct Item 
{ 
int itemId; 
char description[DESC_SIZE]; 
double cost, price; 
}; 

int processFile(const char* saifFile, const char* raofFile) 
{ 
fstream outFile, inFile; 
Item Inventory; 

inFile.open(saifFile, ios::in); 
while (inFile) 
    { 
     inFile >> Inventory.itemId >> Inventory.cost >> Inventory.price; 
     inFile.getline(Inventory.description, DESC_SIZE); 
     cout << "  " << Inventory.itemId << "  " << setw(5) << Inventory.cost << "  " << setw(5) << Inventory.price <<" " << Inventory.description << endl; 
    } 

return 0; 
} 
+3

你可以發佈你正在閱讀的文件的內容嗎? –

+0

更喜歡使用'Inventory.description = std :: getline(infile)',所以你不必擔心緩衝區大小。 –

+0

是'DESC_SIZE'的任意大小? – 109

回答

-1

嘗試改變,同時聲明:

while(!inFile.eof()) 

,並且確保您已存儲在正確的順序文件中的數據。

+0

[爲什麼iostream :: eof考慮循環條件錯誤?](http://stackoverflow.com/questions/5605125/why-is-iostreameof-inside-a-loop-condition-considered-wrong) –

+0

@MooingDuck,這個線程回答您的查詢: http:// stackoverflow .com/questions/5837639/eof-bad-practice – user3566211

+2

對不起,這是一個SO問題的鏈接,解釋了爲什麼我downvoted。這並不是一個真正的問題。對困惑感到抱歉。 –

0

確保您設置爲從​​接收的數據類型與​​讀取的類型相匹配。如果沒有,你會得到一個流錯誤,這將導致你的程序停止閱讀。

每次閱讀後,嘗試到inFile.clear()並查看您的程序是否提前掛起或停止。或者,每次讀取後嘗試

if(inFile.fail()) 
{ 
    cout << "Read error in file\n"; 
} 

這可能不是答案,但我會在這裏開始調試。

相關問題