I've looked at the other getline questions and couldn't come up with a solution. I will have a file formatted like so:
book
author
book
author
...
The code is to read the book title into the struct at book.name, and then the author at book.author but what I am getting is a blank for book and only author is printing. I know it's overwriting book.name but I'm not sure how to remedy it.
#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: works with vectors now, too, though I've not been able to get it as fancy as the answer below, this is at least a bit more understandable for my level of C++ at the 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;
}
You should change
while(!file.eof()){
getline(file,books[0].name);
getline(file,books[0].author);
}
to
int i = 0;
while(getline(file,books[i].name) && getline(file,books[i].author) && ++i < 100);
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.