-1

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

madaniloff
  • 57
  • 9
  • 1
    Clearly the answer is to read two words at a time, e.g. `while (file >> str1 >> str2) { b[count].title = str1; b[count].author = str2; count++; }` – john Jan 09 '21 at 09:16

1 Answers1

3

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++;
    }
}
Lukas-T
  • 11,133
  • 3
  • 20
  • 30
  • Thank you! So the text file actually has more fields than author and title, it also has page numbers. So what would be a way to convert the file input string into an int? Could I do file >> std:::stoi(b[count].pages)? – madaniloff Jan 09 '21 at 18:38
  • `file >> b[count].pages` will be sufficient. It works just like you would read input from `std::cin`. – Lukas-T Jan 09 '21 at 19:37