Help with classes,arrays, text.

Hello to everyone reading this. I have a project due within a week and I'm having some difficulty reading from text files. I have a class named Book and within Book I have several private member variables. In main I have to create several objects of type Book, 45 to be exact. I have in main, Book books[45];
The biggest problem is I need to read a text file and store words and numbers into the private member variables. After storing them I will 45 different books. How do I go about reading the numbers and words, one by one then placing them within the private variables?
Last edited on
Take a look at filestreams:
http://www.cplusplus.com/reference/iostream/fstream/

Also, for something like this strings will be your friend. Saves a lot of micro management:
http://www.cplusplus.com/reference/string/string/
Heres an empty shell of what you might need to do, if you have any questions just ask.

main.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
#include <fstream>
//create a constant to use in the Array size
#define EXIT_SUCCESS 0 //easy code reading
#define EXIT_FAILURE 1
using namespace std; //optional, considered "lazy"
void ReadInfile(Book ObjArr[]); //Make a function to read in the book file
int main()
{
    //create your array
    //call function
    return EXIT_SUCCESS;
}

void ReadInfile(Book ObjArr[])
{
    //create copies of your varibes(e.g. int pages, string title)
    std::ifstream InFile("NAME_OF_FILE");
    for(int i = 0; i < ArrSIZE;i++) //create a for loop to read in
    {
        //if not at eof
        {
                //read file into varibles you declared above
                //call functions that set values using the variables read into
        }
    }
}

book.h
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
#ifndef BOOK_H
#define BOOK_H
#include <string>
#include <iostream>
#include <fstream>
class Book
{
    public: 
        //set functions to modify private varibles, E.g.
        //void SetFirstName(std::string Name);
        //other public functions you'll use
    protected:
    private:
        //book varibles
};

#endif // BOOK_H 


book.cpp
1
2
3
4
#include "Book.h"
#include <iostream>
#include <string>
//include functions you will use throughout the program to modify the books 
Last edited on
Thanks Need4Sleep and BlackSheep, but I still have a problem. I haven't learned how to use "std::" just yet, which means I can't use it for this assignment. My problem is, how exactly would I put the txt file variables into the private variables? I will have the class "Book" and the object "books" with an array size of 45. I know how to write a function to put the variables into the private members, but how would I do so for let's say books[32] or books[2]. I don't want to have 45 objects of class Book because that's just tedious.
Topic archived. No new replies allowed.