Solved

c++ calculating book age

Posted on 2012-04-12
10
290 Views
Last Modified: 2012-04-19
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
Comment
Question by:tomatoes_program
  • 5
  • 5
10 Comments
 
LVL 86

Accepted Solution

by:
jkr earned 500 total points
ID: 37840723
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
 

Author Comment

by:tomatoes_program
ID: 37840812
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
 
LVL 86

Assisted Solution

by:jkr
jkr earned 500 total points
ID: 37840835
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
 

Author Comment

by:tomatoes_program
ID: 37840969
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
 
LVL 86

Expert Comment

by:jkr
ID: 37840983
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
Is Your Active Directory as Secure as You Think?

More than 75% of all records are compromised because of the loss or theft of a privileged credential. Experts have been exploring Active Directory infrastructure to identify key threats and establish best practices for keeping data safe. Attend this month’s webinar to learn more.

 

Author Comment

by:tomatoes_program
ID: 37840987
I do coding on my old trusty xp pentium 4 computer still, unfortunately.
It's not so trusty any more..
0
 
LVL 86

Expert Comment

by:jkr
ID: 37841013
I can assure you that you are certainly not ging to crash it that way ;o)
0
 

Author Comment

by:tomatoes_program
ID: 37841018
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
 

Author Comment

by:tomatoes_program
ID: 37841058
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
 
LVL 86

Expert Comment

by:jkr
ID: 37845443
Hmm, doesn't look that bad - what errors are you getting?
0

Featured Post

Is Your Active Directory as Secure as You Think?

More than 75% of all records are compromised because of the loss or theft of a privileged credential. Experts have been exploring Active Directory infrastructure to identify key threats and establish best practices for keeping data safe. Attend this month’s webinar to learn more.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Unlike C#, C++ doesn't have native support for sealing classes (so they cannot be sub-classed). At the cost of a virtual base class pointer it is possible to implement a pseudo sealing mechanism The trick is to virtually inherit from a base class…
Go is an acronym of golang, is a programming language developed Google in 2007. Go is a new language that is mostly in the C family, with significant input from Pascal/Modula/Oberon family. Hence Go arisen as low-level language with fast compilation…
The goal of the tutorial is to teach the user how to use functions in C++. The video will cover how to define functions, how to call functions and how to create functions prototypes. Microsoft Visual C++ 2010 Express will be used as a text editor an…
The viewer will learn how to clear a vector as well as how to detect empty vectors in C++.

863 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

26 Experts available now in Live!

Get 1:1 Help Now