Solved

c++ calculating book age

Posted on 2012-04-12
10
287 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
How your wiki can always stay up-to-date

Quip doubles as a “living” wiki and a project management tool that evolves with your organization. As you finish projects in Quip, the work remains, easily accessible to all team members, new and old.
- Increase transparency
- Onboard new hires faster
- Access from mobile/offline

 

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

6 Surprising Benefits of Threat Intelligence

All sorts of threat intelligence is available on the web. Intelligence you can learn from, and use to anticipate and prepare for future attacks.

Join & Write a Comment

Introduction This article is the first in a series of articles about the C/C++ Visual Studio Express debugger.  It provides a quick start guide in using the debugger. Part 2 focuses on additional topics in breakpoints.  Lastly, Part 3 focuses on th…
  Included as part of the C++ Standard Template Library (STL) is a collection of generic containers. Each of these containers serves a different purpose and has different pros and cons. It is often difficult to decide which container to use and …
The goal of the video will be to teach the user the concept of local variables and scope. An example of a locally defined variable will be given as well as an explanation of what scope is in C++. The local variable and concept of scope will be relat…
The viewer will learn additional member functions of the vector class. Specifically, the capacity and swap member functions will be introduced.

760 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

20 Experts available now in Live!

Get 1:1 Help Now