Solved

c++ calculating book age

Posted on 2012-04-12
10
298 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
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
  • 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
Industry Leaders: We Want Your Opinion!

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

 

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
 

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

On Demand Webinar - Networking for the Cloud Era

This webinar discusses:
-Common barriers companies experience when moving to the cloud
-How SD-WAN changes the way we look at networks
-Best practices customers should employ moving forward with cloud migration
-What happens behind the scenes of SteelConnect’s one-click button

Question has a verified solution.

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

Suggested Solutions

In days of old, returning something by value from a function in C++ was necessarily avoided because it would, invariably, involve one or even two copies of the object being created and potentially costly calls to a copy-constructor and destructor. A…
Introduction This article is a continuation of the C/C++ Visual Studio Express debugger series. Part 1 provided a quick start guide in using the debugger. Part 2 focused on additional topics in breakpoints. As your assignments become a little more …
The viewer will learn additional member functions of the vector class. Specifically, the capacity and swap member functions will be introduced.
The viewer will be introduced to the technique of using vectors in C++. The video will cover how to define a vector, store values in the vector and retrieve data from the values stored in the vector.

730 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