2012-11-16 52 views
0

,所以這是我的文本文件:申請凍結,而在C++中,從文件中讀取

 
Computer Science 
4 
345848534 
1 
Ivan Ivanov 
Georgi Georgiev 
Plamen Angelov 
====== 
Oreily 
5th avenue, London 
44384208434 
***************** 
Biology 
2 
58934673 
0 
Georgi Ivanov 
Nikolay Stamatov 
Jack Johnson 
====== 
Head first 
Stanley Str 4, Manchester 
449348344 

這是我的功能從文件中讀取:

void ApprovedBook::read_from_file() { 
fstream file; 
string heading; int edition; long ISBN = 0L; bool isApproved = 0; // temp values for each book 
string name; string address; long telephone = 0L; // temp values for manufacturer of the book 
vector<string> authors; // temp vector for authors of the book 
string line; 

file.open("books.txt", ios::in | ios::app); 

while (file.good()) { 
    for (int i=1; i<=NUM_ITEMS; i++) { 
     getline(file, line); 
     switch (i) { 
     case 1: 
      heading = line; break; 
     case 2: 
      edition = atoi(line.c_str()); break; 
     case 3: 
      ISBN = atol(line.c_str()); break; 
     case 4: 
      isApproved = (bool) atoi(line.c_str()); break; 
     } 
    } 

    getline(file, line); 
    while (line != "======") { 
     authors.push_back(line); 
     getline(file,line); 
    } 

    int i = 1; 
    getline(file, line); 
    while (line != "*****************") { 
     switch (i) { 
     case 1: 
      name = line; break; 
     case 2: 
      address = line; break; 
     case 3: 
      telephone = atol(line.c_str()); break; 
     } 

     getline(file, line); 
     i++; 
    } 

    Manufacturer m(name, address, telephone); 
    ApprovedBook a(heading, authors, edition, ISBN, m, isApproved); 
    cout << a << endl; 
    authors.clear(); 
} 

file.close(); 
} 

所以我分開需要的信息用* **構建一個「ApprovedBook」對象。需要「=====」和星星之間的界限來構建一個「製造商」對象,這也是ApprovedBook的一個屬性。所以我讀了第一條信息並輸出對象< <(我已經預定義了該類的運算符)。但在此之後,應用程序凍結,似乎不讀取星星下方的下一條信息。那有什麼問題? file.good()條件是否足夠,或者需要更高級的檢查?

+0

'ios :: in | ios :: app'沒有任何意義,標誌是互斥的。 –

+0

我只留下ios :: in,但沒有任何變化。 –

+0

['while(!stream.eof())'和'while(stream.good())'幾乎總是錯的](http://www.parashift.com/c++-faq-lite/input-output。 html#faq-15.5)(這些是從哪裏來的?!?!?!?!?!) –

回答

0

我替換而file.good和對我工作的罰款(行=「」!)。

0

while (line != "*****************") {對於最後一條記錄始終爲真,除非您在輸入文件的末尾添加星號。

+0

我添加了星星,現在它讀取了第二部分,但仍然凍結。 –

0

在我看來,你將需要此行來檢查文件,以及:

while (file.good() && line != "*****************") { 
+0

這樣它只讀取文件的第一部分。我考慮添加一些特殊的行,如「_________」或別的東西來標記文件的結尾,但因爲我將在稍後添加信息,所以這不起作用。我想知道是否所有這些檢查EOF像!file.eof或file.good()不起作用,那麼會怎樣... –