• Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 306
  • Last Modified:

c++ calculating book age

Hi guys, I just want a push in the right direction for a problem I'm having to calculate the ages of multiple books given in a text file (Title, Author, year of publication, dewey number).

I have to calculate the age from the year of publication and then display all the books and their details (title, author, year, dewey, and age) with the oldest on the top.

an example of the .txt file where the book details are stored is:

Jane Eyre
Charlotte Bronte
1847
521.34
Biggles of the Camel Squadron
Capt W.E. Johns
1934
389.34

Here is my code so far
#include <iostream>
#include <fstream>
#include <string>

using namespace std;

int main () {
string line;
ifstream file ("books.txt");
if (file.is_open())
{
while ( file.good() )
{
getline (file,line);
cout << line << endl;
}
file.close();
}

else cout << "File cannot be opened"; 
system("pause");
return 0;
}

Open in new window


I dunno where to add the classes for the calculations with all functions..

any help is greatly appreciated

****

The original question is:

Setup a class to store a book. The data is to include title, author, year of publication, dewey number and age. The class should include functions to read title, author, year and dewey number from a file, to determine the age of the book and to display that book’s details on screen. The main program should contain an array of book objects which are used in conjunction with the file to load all books from the file.
0
tomatoes_program
Asked:
tomatoes_program
  • 5
  • 5
2 Solutions
 
jkrCommented:
Well, I'd create a class that has a constructor which takes the ifstream as a parameter, so it can read the four lines and store them accordingly, i.e.

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

using namespace std;


class Book {

public:

  Book(ifstream& is) {

     // read four lines:
     for (int i = 0; i < 4; ++i) {

       string line;

       getline(is,line);

       // process line accordingly to assign it to a member, e.g. with a 'switch' statement
    }

  }

};

int main () {
string line;
ifstream file ("books.txt");
if (file.is_open())
{
while ( file.good() )
{
getline (file,line);
cout << line << endl;
}
file.close();
}

else cout << "File cannot be opened"; 
system("pause");
return 0;
}
                                  

Open in new window

0
 
tomatoes_programAuthor Commented:
Oh thank you!!
I haven't implemented it yet but do you think something like this would be appropriate?

{
      string t; //title
      string a; //author
      int y; //year
      int d; //dewey
      float o; //age
      
      public:
        
      void createbooklist(string a,string b,int c, int d,float e)
      {
            t=a;
            a=b;
            y=c;
            d=d;
            o=e;
      }

Open in new window

0
 
jkrCommented:
Wel, I'm OK with the class , yet not sure why you'd need a 'createbooklist()' method - you can just read the lines in your constructor, assign the member variables accordingly and then add the 'Book' object you just created to either a 'std::list<Book>' or a 'std::vector<Book>', depending on what makes more sense for your task. And that definitely should not be done by any member function ('Book' is the 'controlled object' in that context, not the acting one), but from within your code, whre you are creating the instances.
0
Concerto's Cloud Advisory Services

Want to avoid the missteps to gaining all the benefits of the cloud? Learn more about the different assessment options from our Cloud Advisory team.

 
tomatoes_programAuthor Commented:
ughh, I had it right after a lot of trial and error, flicking through multiple books and what not and finally when I compiled it, the computer froze and I saw the beautiful blue screen of death. Now, I have to install windows again and most probably all the hard brain exploding work was for nothing. I'm pretty sure my code made my computer flip!

Is there such a possibility?
0
 
jkrCommented:
A BSOD? From User Mode code? Certainy not ;o)

The worst thing to happen woud be your program being shut down for an "out of memory condition", but anything else is unikely on modern operating systems.
0
 
tomatoes_programAuthor Commented:
I do coding on my old trusty xp pentium 4 computer still, unfortunately.
It's not so trusty any more..
0
 
jkrCommented:
I can assure you that you are certainly not ging to crash it that way ;o)
0
 
tomatoes_programAuthor Commented:
lol. Thanks for your help by the way! I think I will be failing this task, only got an hour to complete it now, but have to fix the computer first to get the rest of the tasks back too..
0
 
tomatoes_programAuthor Commented:
all right, so far I got this from what I understood, manipulating your help, but it looks very bad with more then 40 errors. The book I used is java, so that has a lot to do with the errors.

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

using namespace std;

class Book
{
private:
std::string title;
std::string author;
int yearOfPublication;
std::string deweyNumber;
int age;

//Constructors
public:
Book();

Book(const std::string &title, const std::string &author, int yearOfPublication, const std::string &deweyNumber);

Book(const std::string &title, const std::string &author, int yearOfPublication, const std::string &deweyNumber, int age);

//setters
virtual void setTitle(const std::string &title);
virtual void setAuthor(const std::string &author);
virtual void setYearOfPublication(int yearOfPublication);

virtual void setDeweyNumber(const std::string &deweyNumber);

virtual void setAge(int age);

//getters
virtual std::string getTitle();
virtual std::string getAuthor();
virtual int getYearOfPublication();
virtual std::string getDeweyNumber();
virtual int getAge();
//This method is called when you try to print the details of a book
//using System.out.println(aReferenceToABookObject);

virtual std::string ToString();

};

class Library
{
public:

	static int num; // number of books in library;
	static Book books[20];

	static void main(std::string args[]);

	static void makeBook();

};

Book::Book()
{
}

Book::Book(const std::string &title, const std::string &author, int yearOfPublication, const std::string &deweyNumber)
{
this->title = title;
this->author = author;
this->yearOfPublication = yearOfPublication;
this->deweyNumber = deweyNumber;


this->age = 2012 - yearOfPublication;

}

Book::Book(const std::string &title, const std::string &author, int yearOfPublication, const std::string &deweyNumber, int age)
{
this->title = title;
this->author = author;
this->yearOfPublication = yearOfPublication;
this->deweyNumber = deweyNumber;
this->age = age;

}

void Book::setTitle(const std::string &title)
{
	this->title = title;
}

void Book::setAuthor(const std::string &author)
{
	this->author = author;
}

void Book::setYearOfPublication(int yearOfPublication)
{
if (yearOfPublication >= 0)
{
this->yearOfPublication = yearOfPublication;
}
}

void Book::setDeweyNumber(const std::string &deweyNumber)
{
	this->deweyNumber = deweyNumber;
}

void Book::setAge(int age)
{
if (age >= 0)
{
this->age = age;
}
}

std::string Book::getTitle()
{
	return title;
}

std::string Book::getAuthor()
{
	return author;
}

int Book::getYearOfPublication()
{
	return yearOfPublication;
}

std::string Book::getDeweyNumber()
{
	return deweyNumber;
}

int Book::getAge()
{
	return age;
}

std::string Book::ToString()
{
std::string details = "\nTitle: " + title + "\nAuthor: " + author + "\nYear: " + "\nDewey Number: " + deweyNumber + "\nAge: ";
return details;
}


int Library::num = 0;

void Library::main(std::string args[])
{
	puts("Welcom to the library!");

	try
	{
                 
    		// Open the file.
string line;
ifstream file ("books.txt");


		std::string strLine;



			//Read the file line by line
			while ((strLine = readLine()) != 0)
			{
				allLines.push_back(strLine);
				if (allLines.size() > 4)
				{
					makeBook();
					allLines.clear();
				}

			}

			//Close the input stream
			in_Renamed->close();

	}
		catch (Exception *e)
		{
			System::err::println("Error: " + e->getMessage());
		}

		//Display all the books
		for (int i = 0; i < sizeof(books) / sizeof(books[0]); i++)
		{
			if (books[i] != 0)
			{
				puts(books[i]);
			}

		}

}

void Library::makeBook()
{
	std::string d1 = "";
	std::string d2 = "";
	int d3 = 0;
	std::string d4 = "";


	for (int i = 0; i < 4 ; i++)
	{
		switch (i)
		{
			case 0:
			d1 = allLines[0];
			break;

			case 1:
			d2 = allLines[1];
			break;

			case 2:
			d3 = StringConverterHelper::fromString<int>(allLines[2]);
			break;

			case 3:
			d4 = allLines[3];
			break;

		}

	}

	if (num < sizeof(books) / sizeof(books[0]))
	{
		books[num] = new Book(d1,d2,d3,d4);
		num++;
	}

}

Open in new window


can this code be saved?
0
 
jkrCommented:
Hmm, doesn't look that bad - what errors are you getting?
0

Featured Post

Concerto's Cloud Advisory Services

Want to avoid the missteps to gaining all the benefits of the cloud? Learn more about the different assessment options from our Cloud Advisory team.

  • 5
  • 5
Tackle projects and never again get stuck behind a technical roadblock.
Join Now