Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

[C++ Code] Reading from a file to an object, then storing it in an array So I ha

ID: 3701531 • Letter: #

Question

[C++ Code] Reading from a file to an object, then storing it in an array

So I have a class, Book, as shown below. My question is how do I read from a file called ‘input.data’ to create a Book object from each line (see example input.dat below)? As each Book object is created, how do I store it in an array of the type Book.

Example input.dat

000001, Bjarne Stroustrup, The C++ Programming Language, 4, 2013, 0321563840

000002, Stephen Colbert, Stephen Colbert's Midnight Confessions, 1, 2017, 1501169009

000003, Tom Clancy, The Hunt for Red October, 2, 1984, 0425240339

000004, Gregory Dudek, Computational Principles of Mobile Robotics, 2, 2010, 0521692121

class Book t public: Book (); Book(string id, string auth, string tit, int ed, int yr, string isbn); private: string book_id; string author; string title; int edition; int pub_year; string ISBN;

Explanation / Answer

/****** I have provided the complete code which read the input file input.dat . just provide the complete location of the file like i have given. It reads the file and convert each line to Book Object and stores in the array of Book Object

*****/

#include<iostream>
#include<string.h>
#include<fstream>
#include<sstream>
#include<vector>
#include<stdlib.h>
using namespace std;


class Book{
public:
  Book();
  Book(string id, string auth, string tit, int ed, int yr, string isbn);
  
private:
  string book_id;
  string author;
  string title;
  int edition;
  int pub_year;
  string ISBN;
};


Book :: Book(){

}
Book :: Book(string id, string auth, string tit, int ed, int yr, string isbn){
book_id = id;
author = auth;
title = tit;
edition = ed;
pub_year = yr;
ISBN = isbn;
}


int main(){
ifstream infile("E:\input.dat");
Book book_array[25];
int i=0;
for(string line; getline(infile, line);){
  string tok;
  stringstream ss(line);
  vector<string> internal;
  while(getline(ss,tok, ',')){
   internal.push_back(tok);
  }
  
  
  if(internal.size() > 0){
   string id = internal[0];
   string auth = internal[1];
   string tit = internal[2];
   int ed = atoi(internal[3].c_str());
   int yr = atoi(internal[4].c_str());
   string isbn = internal[5];
   Book book = Book(id, auth, tit, ed, yr, isbn);
   book_array[i++] = book;
  }
}




return 0;

}

Hire Me For All Your Tutoring Needs
Integrity-first tutoring: clear explanations, guidance, and feedback.
Drop an Email at
drjack9650@gmail.com
Chat Now And Get Quote