Search code examples
c++filestructifstreameof

How to read in from a file word by word and assign those words to a struct?


In my project I have a .txt file that has the number of books at the top, and then title of a book and its author separated by a space, so for example:

1
Elementary_Particles Michel_Houllebecq

I then have a struct for the book object

struct book {
    string title;
    string author;
};

There is a book array of these book objects to since there are multiple books and authors. What I need to do is to read in these word by word and assign the title to book.title and the author to book.author. This is what I have so far:

void getBookData(book* b, int n, ifstream& file) { //n being the number at the top of the file
    int count = 0;
    string file_string;
    while(!file.eof() && count != n-1) {
       while (file >> file_string) {
           b[count].title = file_string;
           b[count].author = file_string;
           count++;
   }
}

When I run this with these outputs:

cout << book[0].title << endl;
cout << book[0].author << endl;

I get:

Elementary_Particles
Elementary_Particles

Basically it is only taking the first word. How do I make it so that the first word will be assigned to book.title and the next one after to book.author?

Thank you


Solution

  • In this piece of code

    while (file >> file_string) {
          b[count].title = file_string;
          b[count].author = file_string;
          count++;
    }
    

    you read one word and assign the same value to title and author, don't expect the compiler to guess your intentions ;)

    Some additional hints and ideas:

    while(!file.eof() is not what you want, instead put the input operations into the loop condition. And you can skip the intermediate string and read directly into title/author:

    void getBookData(book* b, int n, ifstream& file) {
        int count = 0;
        while((file >> b[count].title >> b[count].author) && count != n-1) {
            count++;
        }
    }