2016-05-27 10 views
1

Ich habe mir die anderen getline-Fragen angeschaut und konnte mir keine Lösung einfallen lassen. Ich will eine Datei wie so formatiert haben:getline (Datei, Array) bewegt sich nicht zur nächsten Zeile

book 
author 
book 
author 
... 

Der Code ist auf den Buchtitel in die Struktur bei book.name zu lesen, und dann an dem Autor book.author aber was ich bin immer ein Rohling für Buch und nur Autor druckt. Ich weiß, dass es book.name überschreibt, aber ich bin nicht sicher, wie ich es beheben soll.

#include <string> 
#include <fstream> 
using namespace std; 

struct Books { 
    string name; 
    string author; 
}; 

Books books[100]; 


int main(){ 
    fstream file; 
    file.open("test.txt"); 

    while(!file.eof()){ 
     getline(file,books[0].name); 
     getline(file,books[0].author); 
    } 
    file.close(); 
    cout << books[0].name << " " << books[0].author << endl; 

    return 0; 
} 

Update: Jetzt mit Vektoren arbeiten, auch wenn ich nicht in der Lage gewesen war darunter so schick wie die Antwort zu bekommen, ist dies zumindest ein bisschen verständliche für mein Niveau von C++ im Moment.

struct book_meta_data { 
    string name; 
    string author; 
}; 
int i = 0; 
book_meta_data b; 
while (getline(f,b.name) && getline(f,b.author) && 
     ++i){ 
     books.push_back(b); 
     } 

cout << books.size() << endl; 
for (vector<int>::size_type i = 0; i != books.size(); i++){ 
    cout << books[i].name << " " << books[i].author << endl; 
} 
+1

See [warum 'while (! File.eof())' ist falsch] (http://stackoverflow.com/ Fragen/5605125/why-is-iostreameof-inside-a-loop-bedingung-falsch-betrachtet) – Barmar

Antwort

0

sollten Sie

ändern
while(!file.eof()){ 
    getline(file,books[0].name); 
    getline(file,books[0].author); 
} 

zu

int i = 0; 
while(getline(file,books[i].name) && getline(file,books[i].author) && ++i < 100); 
+0

Können Sie erklären, warum das funktioniert? Vielleicht ein Zusammenhang? –

+0

das hat funktioniert, ich forsche warum, aber danke. –

+0

@AlexandarNarayan [Irgendein Kontext] (http://stackoverflow.com/questions/5605125/why-is-iostreameof-inside-a-loop-condition-conspired-wrong) –