jwest91 jwest91 - 2 months ago 23
C++ Question

Using getline() to read input (with spaces) from file into a structure

I am currently in a C++ data structures class and I am extremely new to c++. My goal here is to read lines from a file and store them into a structure. The lines contain elements of a book. My problem is that some lines have spaces, and I'm not sure how to properly read them into a structure. I can't seem to use geline() correctly to read the lines into each element of the structure. If I run it as is, I get the message "error: expected primary expression before 'infile'" Apologies if this post isn't formatted correctly, this is also my first stack overflow post! Any help??

This is what my structure looks like:

typedef struct book{
char title[100];
char author[100];
char publisher[100];
float price;
char isbn[100];
int pages;
int copies;
} Book;

And this is how I am trying to read lines into the structure:

for (int i=0; i < currentIndex; i++)
getline(ifstream infile, my_book[i].title);
getline(ifstream infile, my_book[i].author);
getline(ifstream infile, my_book[i].publisher);
getline(ifstream infile, my_book[i].price);
getline(ifstream infile, my_book[i].isbn);
getline(ifstream infile, my_book[i].pages);
getline(ifstream infile, my_book[i].copies);

The text file will have book information listed as such:

Magician: Apprentice
Raymond E. Feist
Spectra (January 1, 1994)


1 - first declare infile outside for loop then use it.

2 - getline(infile, book[i]....) is not infile.getline(book[i]... , size,..) the first is used with class string and the second is used with array of characters.

so your program may look like:

ifstream infile("data.txt", ios::in); // your data file

for (int i=0; i < currentIndex; i++)
       infile.getline(my_book[i].title    , 100, '\n');
       infile.getline(my_book[i].author   , 100, '\n');
       infile.getline(my_book[i].publisher, 100, '\n');
       infile >> my_book[i].price;
       infile.getline(my_book[i].isbn     , 100, '\n');
       infile >> my_book[i].pages;
       infile >> my_book[i].copies;