PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Saturday, October 29, 2022

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

 October 29, 2022     c++, eof, file, ifstream, struct     No comments   

Issue

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++;
    }
}


Answered By - churill
Answer Checked By - Dawn Plyler (PHPFixing Volunteer)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing