C. Timmerman
C. Timmerman

Reputation: 37

Need help reading data from .txt file into an array C++

#include <iostream>
#include <fstream>
#include <string>

struct textbook //Declare struct type
{
    int ISBN;
    string title;
    string author;
    string publisher;
    int quantity;
    double price;
};

// Constants
const int MAX_SIZE = 100;

// Arrays
textbook inventory[MAX_SIZE];

void readInventory()
{
    // Open inventory file
    ifstream inFile("inventory.txt");

    // Check for error
    if (inFile.fail())
    {
        cerr << "Error opening file" << endl;
        exit(1);
    }

    // Loop that reads contents of file into the inventory array.

       pos = 0; //position in the array

       while (

        inFile >> inventory[pos].ISBN
               >> inventory[pos].title
               >> inventory[pos].author 
                   >> inventory[pos].publisher
               >> inventory[pos].quantity 
                   >> inventory[pos].price
          )

    {
        pos++;

    } 

    // Close file 
    inFile.close();

    return;

}

Hello,

I need assistance with this function. The goal of this function is to read in the information from a txt file and read it in to an array struct for a textbook. The text file itself is already set up in the correct order for the loop.

My problem is that for the title section, the title of a book might be multiple words like 'My first book" for example. I know that I have to use a getline to take the line as a string to feed it into the 'title' data type.

I am also missing a inFile.ignore() somewhere but I don not know how to put it into a loop.

Upvotes: 0

Views: 879

Answers (1)

Ziezi
Ziezi

Reputation: 6457

Presuming the input format is:

ISBN title author publisher price quantity price

i.e., the data members are line white space separated, you could define operator>> for your struct textbook, which could look something like:

std::istream& operator>> (std::istream& is, textbook& t)
{
    if (!is) // check input stream status
    {
        return is;
    }

    int ISBN;
    std::string title;
    std::string author;
    std::string publisher;
    int quantity;
    double price;

    // simple format check
    if (is >> ISBN >> title >> author >> publisher >> quantity >> price)
    {
          // assuming you additionally define a (assignment) constructor  
          t = textbook(ISBN, title, author, publisher, quantity, price);

          return is;
    }

    return is;
}

Then to read your file you simply do:

std::ifstream ifs(...);

std::vector<textbook> books;

textbook b; 
while (ifs >> b)
{
     books.push_back(b);
}

Regarding the use of getline() see this answer.


Upvotes: -1

Related Questions