I'm very new to programming and I am trying to write a program that adds and subtracts polynomials. My program sometimes works, but most of the time, it randomly crashes and I have no idea why. It's very buggy and has other problems I'm trying to fix, but I am unable to really get any further coding done since it crashes. I'm completely new here but any help would be greatly appreciated.
Here's the code:
#include <iostream>
#include <cstdlib>
using namespace std;
int getChoice();
class Polynomial10
{
private:
double* coef;
int degreePoly;
public:
Polynomial10(int max); //Constructor for a new Polynomial10
int getDegree(){return degreePoly;};
void print(); //Print the polynomial in standard form
void read(); //Read a polynomial from the user
void add(const Polynomial10& pol); //Add a polynomial
void multc(double factor); //Multiply the poly by scalar
void subtract(const Polynomial10& pol); //Subtract polynom
};
void Polynomial10::read()
{
cout << "Enter degree of a polynom between 1 and 10 : ";
cin >> degreePoly;
cout << "Enter space separated coefficients starting from highest degree" << endl;
for (int i = 0; i <= degreePoly; i++) cin >> coef[i];
}
void Polynomial10::print()
{
for (int i = 0;i <= degreePoly; i++) {
if (coef[i] == 0) cout << "";
else if (i >= 0) {
if (coef[i] > 0 && i != 0) cout<<"+";
if ((coef[i] != 1 && coef[i] != -1) || i == degreePoly) cout << coef[i];
if ((coef[i] != 1 && coef[i] != -1) && i != degreePoly ) cout << "*";
if (i != degreePoly && coef[i] == -1) cout << "-";
if (i != degreePoly) cout << "x";
if ((degreePoly - i) != 1 && i != degreePoly) {
cout << "^";
cout << degreePoly-i;
}
}
}
}
void Polynomial10::add(const Polynomial10& pol)
{
for(int i = 0; i<degreePoly; i++) {
int degree = degreePoly;
coef[degreePoly-i] += pol.coef[degreePoly-(i+1)];
}
}
void Polynomial10::subtract(const Polynomial10& pol)
{
for(int i = 0; i<degreePoly; i++) {
coef[degreePoly-i] -= pol.coef[degreePoly-(i+1)];
}
}
void Polynomial10::multc(double factor)
{
//int degreePoly=0;
//double coef[degreePoly];
cout << "Enter the scalar multiplier : ";
cin >> factor;
for(int i = 0; i<degreePoly; i++) coef[i] *= factor;
}
Polynomial10::Polynomial10(int max)
{
degreePoly = max;
coef = new double[degreePoly];
for(int i; i < degreePoly; i++) coef[i] = 0;
}
int main()
{
int choice;
Polynomial10 p1(1),p2(1);
cout << endl << "CGS 2421: The Polynomial10 Class" << endl << endl << endl;
cout
<< "0. Quit\n"
<< "1. Enter polynomial\n"
<< "2. Print polynomial\n"
<< "3. Add another polynomial\n"
<< "4. Subtract another polynomial\n"
<< "5. Multiply by scalar\n\n";
int choiceFirst = getChoice();
if (choiceFirst != 1) {
cout << "Enter a Polynomial first!";
}
if (choiceFirst == 1) {choiceFirst = choice;}
while(choice != 0) {
switch(choice) {
case 0:
return 0;
case 1:
p1.read();
break;
case 2:
p1.print();
break;
case 3:
p2.read();
p1.add(p2);
cout << "Updated Polynomial: ";
p1.print();
break;
case 4:
p2.read();
p1.subtract(p2);
cout << "Updated Polynomial: ";
p1.print();
break;
case 5:
p1.multc(10);
cout << "Updated Polynomial: ";
p1.print();
break;
}
choice = getChoice();
}
return 0;
}
int getChoice()
{
int c;
cout << "\nEnter your choice : ";
cin >> c;
return c;
}
When you create your objects with p1(1) and p2(1) the coef array in each object is allocated to contain one element. Then in read() you simply set degreePoly to a (possibly higher) value but don't change the allocation of coef. It will still contain only one element, but all coefficients are written to it, probably writing over the bounds of the array. Instead the old coefshould be freed and a new array of suitable size be allocated.
Also in add and subtract you are assigning to coefficients out of bounds (for i=0):
coef[degreePoly-i] -= pol.coef[degreePoly-(i+1)];
It also seems wrong mathematically to subtract the coefficients at index degreePoly-(i+1) from those at index degreePoly-i. Additionally the case that the two polygons might have different degrees is currently not handled.
One issue is the coef allocation. You're allocating an array of degreePoly=max elements (1 for the two actual objects). But I think it should be max + 1, since a n-degree polynomial has n + 1 coefficients. This off-by-one error appears elsewhere (e.g. add and mult). Also in the constructor, you are not initializing i, so it has an undefined value, which alone means you can (probably will) write to memory you don't control.
Later, in your read code, you overwrite degreePoly, but do not reallocate coef, so it could be the wrong size, at least if you exceed your maximum. Also note that you are accepting degreePoly + 1 coefficients (which I think is correct) here. This means a max of 1 in the constructor only corresponds to a degreePoly of 0 in read! Entering 1 in read will cause two values to be read, which will overflow the array.
Writing to invalid pointer locations and using uninitialized values causes undefined behavior, which is why it crashes sometimes.
if (choiceFirst == 1) {choiceFirst = choice;}
doesn't make sense since choice is not initialized at this stage. You probably want:
if (choiceFirst == 1) {choice = choiceFirst;}
Related
I have created a project that breaks a big number to its roots, it works very well, but it prints an extra * at the end of the last root.
#include <iostream>
using namespace std;
int multinum(int a, int b);
int primeOp(int a);
int main()
{
char ch;
do {
int a=0, b=0;
multinum(a,b);
cout << "\n\nDo you want to continue?(y/n)";
cin >> ch;
} while (ch=='y');
return 0;
}
int multinum(int num1, int num2)
{
cout<< "\nPlease enter the first number : ";
cin >> num1;
cout << "\nPlease enter the second number : ";
cin >> num2;
cout << num1 <<" = ";
primeOp(num1);
cout << endl;
cout << num2 <<" = ";
primeOp(num2);
return 0;
}
int primeOp(int a)
{
int i, x, power;
x=a;
if (a%2==0)
{
power=0 ;
while(a%2==0)
{
a/=2;
power++;
}
cout << 2 <<"^"<<power<< "*";
}
for (i=3; i<=x/2; i+=2)
{
power=0 ;
while(a%i==0)
{
a/=i;
power++;
}
if (power!=0)
cout << i <<"^"<< power << "*";
if (power!=0 && a%i== 0)
cout << "*";
}
if(a==x)
cout<< x << "^" << 1;
return 0;
}
I tried to print * in different ways but none of them had any effect, I also tried to stop printing by the use of the last "i" or "power" but it was useless.
What should I do, to stop the * bring printed when it's not needed?
Example: 24 = 2^3 * 3^1 * --- it should become: 24 = 2^3*3^1
To be able to print something only sometimes you need to print it under an if, and you need a condition that will control that print. A bool flag should do the trick. The other part of the trick is to print the asterisk before the next component, not after.
void PrintComponent(int root, int power, bool& printStar)
{
if (printStar)
cout << " * ";
cout << root << "^" << power;
printStar = true;
}
int primeOp(int a)
{
int i, x, power;
bool printStar = false;
x = a;
if (a % 2 == 0)
{
...
PrintComponent(2, power, printStar);
}
for (i = 3; i <= x / 2; i += 2)
{
...
if (power != 0)
PrintComponent(i, power, printStar);
}
if (a == x)
PrintComponent(x, 1, printStar);
return 0;
}
If finding the last print is not easy make the first print special.
Print the first power like this:
cout << 2 <<"^"<<power;
Then print all the rest via
cout << "*2^"<<power;
I dont understand your code fully, but to know it is the first print you can use a boolean flag.
You can suppres this issue by printing backspaces at the end of the result.
In primeOp add:
cout <<"\b \b";
Just above return statement
int main() {
cout << "Enter some numbers fam! " << endl;
cout << "If you wanna quit, just press q" << endl;
int n{ 0 };
int product = 1;
char quit = 'q';
while (n != 'q') {
cin >> n;
product = product* n;
cout <<"The product is : " << product << endl;
}
cout << endl;
cout << product;
return 0;
}
Whenever I print it out and cut the code using 'q', it prints me an infinite amount of "The product is 0". Also, how can I print out the final product of all numbers at the end?
So, there are some problems in your code.
First, you are taking input and assigning it to an int, which might not have been a problem, but you are also comparing the int to a char(which will cause problems in your case)
int n{ 0 };
while(n != 'q') {
cin >> n;
}
To solve that, you can make the n a string and then convert it into an integer with stoi(n) to use with the calculation
string n; // don't need to initialize a string, they are initialized by default.
int product = 1;
cin >> n; // Taking input before comparing the results
while(n != "q") { // Had to make q a string to be able to compare with n
product *= stoi(n); // Short for product = product * stoi(n)
cout <<"The product is : " << product << endl;
cin >> n; // Taking input for the next loop round
}
cout << endl;
cout << product;
Ok i've been programming for about a week now, i started with c++. I'm writing a program that is a kind of an arithmetic trainer, you enter the amount of equations you want, you enter your limit for the random number generator, you specify what kind of equations you want(/*-+), then the program uses a for loop and goes through and generates the equations and their answers in a var and then the users input is checked against this var and if they match another var which is counting the right answers is incremented. After the last equation the program tells the user how many they got right out of how many equations, and by dividing the amount of right answers by the amount of questions then multiplying this value by 100 u should obtain the accuracy percentage for this users arithmetic session. Problem is c++ keeps returning to me a friggin 0 value and i cannot for the life of me work out why in the world c++ is doing this.
entire program:
#include <iostream>
#include <string>
#include <ctime>
#include <cstdlib>
using namespace std;
void menu(void);
class session{
public:
session(){
create_session();
}
void create_session(void){
amount = 0;
range_limit = 0;
rights = 0;
answer = 0;
input = 0;
type = "";
while(amount == 0){
cout << "\nHow many equations do you want?: "; cin >> amount;
if(amount < 1){
cout << "\nAmount is too low!";
amount = 0;
}
}
while(range_limit == 0){
cout << "Enter the number range limit: "; cin >> range_limit;
if(range_limit < 1){
cout << "\nRange limit too low!";
range_limit = 0;
}
}
while(type == ""){
cout << "What equation type do you want?: "; cin >> type;
int strlen = type.size();
if(strlen < 1){
cout << "Invalid type input!";
type = "";
}
}
if(type == "+"){
for(int i=0;i<amount;i++){
int a = random();
int b = random();
answer = a + b;
cout << "\n" << a << " + " << b << " = "; cin >> input;
if(answer == input){
rights++;
}
}
}
cout << "\nYou got " << rights << " answers right out of " << amount << " equations." << endl;
cout << "Accuracy percentage: " << getAccuracy() << "%" << endl;
int post_menu=0;
while(post_menu == 0){
cout << "Enter 1 to create another session or 2 to return to the menu: ";
cin >> post_menu;
if(post_menu == 1){
create_session();
}else if(post_menu == 2){
menu();
}else{
cout << "Invalid input: ";
post_menu = 0;
}
}
}
float getAccuracy(){
float x = (rights/amount)*100;
return x;
}
int random(){
int x = 1+(rand()%range_limit);
return x;
}
void set_amount(int a){
amount = a;
}
void set_range_limit(int r){
range_limit = r;
}
void set_rights(int R){
rights = R;
}
void set_answer(int a){
answer = a;
}
void set_input(int i){
input = i;
}
void set_type(string t){
type = t;
}
private:
int amount;
int accuracy;
int range_limit;
int rights;
int answer;
int input;
string type;
};
int main(){
cout << "=== WELCOME TO ARITH! === \n=========================\n";
menu();
return 0;
}
void menu(void){
//Set the seed for random number gen.
srand(time(0));
//Set var for getting menu input, then get the menu input..
int menu_input;
cout << "\n[1]Create a Session. [2]Exit Arith. \nWhat would you like to do?: ";
cin >> menu_input;
//Now we check what the user wants and act accordingly..
if(menu_input > 2){
cout << "error";
menu_input=0;
}else if(menu_input == 1){
session start;
}else if(menu_input == 2){
cout << "\nExiting Arith!";
}else{
cout << "error";
menu_input=0;
}
}
Troublesome part:
float getAccuracy(){
float x = (rights/amount)*100;
return x;
some how the program is returning 0%.
anyone know why this is so and how to get the result im after.
rights and amount both are int , so when you divide the value is floored, for example if you do 5/2 the answer would be 2 instead of 2.5. To solve this you need to cast one of the variable to float like this: (float(rights)/amount) * 100.
when two int numbers are divided the result will also be int even if temporary variable. so you can make any of the variable float or double or cast it.
You need to convert only one data type because the other will be type promoted implicitly.
float x = ((double)rights/amount)*100;
or you can make your amount variable float by default if it doesnt affect any other part of your code.
Also you have the option to static cast:
float x = (static_cast<double>(rights)/amount)*100;
malloc: *** error for object 0x10ee008c0: pointer being freed was not allocated
*** set a breakpoint in malloc_error_break to debug
Abort trap: 6
Or I get this when I try and print everything
Segmentation fault: 11
I'm doing some homework for an OOP class and I've been stuck for a good hour now. I'm getting this error once I've used keyboard input enough. I am not someone who gets frustrated at all, and here I am getting very frustrated with this. Here are the files:
This is the book class. I'm pretty sure this is very solid. But just for reference:
//--------------- BOOK.CPP ---------------
// The class definition for Book.
//
#include <iostream>
#include "book.h"
using namespace std;
Book::Book()
//
{
strcpy(title, " ");
strcpy(author, " ");
type = FICTION;
price = 0;
}
void Book::Set(const char* t, const char* a, Genre g, double p)
{
strcpy(title, t);
strcpy(author, a);
type = g;
price = p;
}
const char* Book::GetTitle() const
{
return title;
}
const char* Book::GetAuthor() const
{
return author;
}
double Book::GetPrice() const
{
return price;
}
Genre Book::GetGenre() const
{
return type;
}
void Book::Display() const
{
int i;
cout << GetTitle();
for (i = strlen(title) + 1; i < 32; i++)
cout << (' ');
cout << GetAuthor();
for (i = strlen(author) + 1; i < 22; i++)
cout << (' ');
switch (GetGenre())
{
case FICTION:
cout << "Fiction ";
break;
case MYSTERY:
cout << "Mystery ";
break;
case SCIFI:
cout << "SciFi ";
break;
case COMPUTER:
cout << "Computer ";
break;
}
cout << "$";
if (GetPrice() < 1000)
cout << " ";
if (GetPrice() < 100)
cout << " ";
if (GetPrice() < 10)
cout << " ";
/* printf("%.2f", GetPrice());*/
cout << '\n';
}
This is the store class that deals with the array and dynamic allocation. This was working well without input commands, but just using its functions it was working like a champ.
//--------------- STORE.CPP ---------------
// The class definition for Store.
//
#include <iostream>
#include <cstring> // for strcmp
#include "store.h"
using namespace std;
Store::Store()
{
maxSize = 5;
currentSize = 0;
bookList = new Book[maxSize];
}
Store::~Store()
// This destructor function for class Store
// deallocates the Store's list of Books
{
delete [] bookList;
}
void Store::Insert(const char* t, const char* a, Genre g, double p)
// Insert a new entry into the direrctory.
{
if (currentSize == maxSize)// If the directory is full, grow it.
Grow();
bookList[currentSize++].Set(t, a, g, p);
}
void Store::Sell(const char* t)
// Sell a book from the store.
{
char name[31];
strcpy(name, t);
int thisEntry = FindBook(name);// Locate the name in the directory.
if (thisEntry == -1)
cout << *name << " not found in directory";
else
{
cashRegister = cashRegister + bookList[thisEntry].GetPrice();
// Shift each succeding element "down" one position in the
// Entry array, thereby deleting the desired entry.
for (int j = thisEntry + 1; j < currentSize; j++)
bookList[j - 1] = bookList[j];
currentSize--;// Decrement the current number of entries.
cout << "Entry removed.\n";
if (currentSize < maxSize - 5)// If the directory is too big, shrink it.
Shrink();
}
}
void Store::Find(const char* x) const
// Display the Store's matches for a title or author.
{
// Prompt the user for a name to be looked up
char name[31];
strcpy(name, x);
int thisBook = FindBook(name);
if (thisBook != -1)
bookList[thisBook].Display();
int thisAuthor = FindAuthor(name, true);
if ((thisBook == -1) && (thisAuthor == -1))
cout << name << " not found in current directory\n";
}
void Store::DisplayGenre(const Genre g) const
{
double genrePrice = 0;
int genreCount = 0;
for (int i = 0; i < currentSize; i++)// Look at each entry.
{
if (bookList[i].GetGenre() == g)
{
bookList[i].Display();
genrePrice = genrePrice + bookList[i].GetPrice();
genreCount++;
}
}
cout << "Number of books in this genre: " << genreCount
<< " " << "Total: $";
if (genrePrice < 1000)
cout << " ";
if (genrePrice < 100)
cout << " ";
if (genrePrice < 10)
cout << " ";
printf("%.2f", genrePrice);
}
void Store::DisplayStore() const
{
if (currentSize >= 1)
{
cout << "**Title**\t\t"
<< "**Author**\t"
<< "**Genre**\t"
<< "**Price**\n\n";
for (int i = 0; i < currentSize; i++)
bookList[i].Display();
}
else
cout << "No books currently in inventory\n\n";
cout << "Total Books = " << currentSize
<< "\nMoney in the register = $";
if (cashRegister < 1000)
cout << " ";
if (cashRegister < 100)
cout << " ";
if (cashRegister < 10)
cout << " ";
printf("%.2f", cashRegister);
cout << '\n';
}
void Store::Sort(char type)
{
Book temp;
for(int i = 0; i <= currentSize; i++)
{
for (int j = i+1; j < currentSize; j++)
{
if (type == 'A')
{
if (strcmp(bookList[i].GetTitle(), bookList[j].GetTitle()) > 0)
{
temp = bookList[i];
bookList[i] = bookList[j];
bookList[j] = temp;
}
}
if (type == 'T')
{
if (strcmp(bookList[i].GetAuthor(), bookList[j].GetAuthor()) > 0)
{
temp = bookList[i];
bookList[i] = bookList[j];
bookList[j] = temp;
}
}
}
}
}
void Store::SetCashRegister(double x)
// Set value of cash register
{
cashRegister = x;
}
void Store::Grow()
// Double the size of the Store's bookList
// by creating a new, larger array of books
// and changing the store's pointer to refer to
// this new array.
{
maxSize = currentSize + 5;// Determine a new size.
cout << "** Array being resized to " << maxSize
<< " allocated slots" << '\n';
Book* newList = new Book[maxSize];// Allocate a new array.
for (int i = 0; i < currentSize; i++)// Copy each entry into
newList[i] = bookList[i];// the new array.
delete [] bookList;// Remove the old array
bookList = newList;// Point old name to new array.
}
void Store::Shrink()
// Divide the size of the Store's bookList in
// half by creating a new, smaller array of books
// and changing the store's pointer to refer to
// this new array.
{
maxSize = maxSize - 5;// Determine a new size.
cout << "** Array being resized to " << maxSize
<< " allocated slots" << '\n';
Book* newList = new Book[maxSize];// Allocate a new array.
for (int i = 0; i < currentSize; i++)// Copy each entry into
newList[i] = bookList[i];// the new array.
delete [] bookList;// Remove the old array
bookList = newList;// Point old name to new array.
}
int Store::FindBook(char* name) const
// Locate a name in the directory. Returns the
// position of the entry list as an integer if found.
// and returns -1 if the entry is not found in the directory.
{
for (int i = 0; i < currentSize; i++)// Look at each entry.
if (strcmp(bookList[i].GetTitle(), name) == 0)
return i;// If found, return position and exit.
return -1;// Return -1 if never found.
}
int Store::FindAuthor(char* name, const bool print) const
// Locate a name in the directory. Returns the
// position of the entry list as an integer if found.
// and returns -1 if the entry is not found in the directory.
{
int returnValue;
for (int i = 0; i < currentSize; i++)// Look at each entry.
if (strcmp(bookList[i].GetAuthor(), name) == 0)
{
if (print == true)
bookList[i].Display();
returnValue = i;// If found, return position and exit.
}
else
returnValue = -1;// Return -1 if never found.
return returnValue;
}
Now this is the guy who needs some work. There may be some stuff blank so ignore that. This one controls all the input, which is the problem I believe.
#include <iostream>
#include "store.h"
using namespace std;
void ShowMenu()
// Display the main program menu.
{
cout << "\n\t\t*** BOOKSTORE MENU ***";
cout << "\n\tA \tAdd a Book to Inventory";
cout << "\n\tF \tFind a book from Inventory";
cout << "\n\tS \tSell a book";
cout << "\n\tD \tDisplay the inventory list";
cout << "\n\tG \tGenre summary";
cout << "\n\tO \tSort inventory list";
cout << "\n\tM \tShow this Menu";
cout << "\n\tX \teXit Program";
}
char GetAChar(const char* promptString)
// Prompt the user and get a single character,
// discarding the Return character.
// Used in GetCommand.
{
char response;// the char to be returned
cout << promptString;// Prompt the user
cin >> response;// Get a char,
response = toupper(response);// and convert it to uppercase
cin.get();// Discard newline char from input.
return response;
}
char Legal(char c)
// Determine if a particular character, c, corresponds
// to a legal menu command. Returns 1 if legal, 0 if not.
// Used in GetCommand.
{
return((c == 'A') || (c == 'F') || (c == 'S') ||
(c == 'D') || (c == 'G') || (c == 'O') ||
(c == 'M') || (c == 'X'));
}
char GetCommand()
// Prompts the user for a menu command until a legal
// command character is entered. Return the command character.
// Calls GetAChar, Legal, ShowMenu.
{
char cmd = GetAChar("\n\n>");// Get a command character.
while (!Legal(cmd))// As long as it's not a legal command,
{// display menu and try again.
cout << "\nIllegal command, please try again . . .";
ShowMenu();
cmd = GetAChar("\n\n>");
}
return cmd;
}
void Add(Store s)
{
char aTitle[31];
char aAuthor[21];
Genre aGenre = FICTION;
double aPrice = 10.00;
cout << "Enter title: ";
cin.getline(aTitle, 30);
cout << "Enter author: ";
cin.getline(aAuthor, 20);
/*
cout << aTitle << " " << aAuthor << "\n";
cout << aGenre << " " << aPrice << '\n';
*/
s.Insert(aTitle, aAuthor, aGenre, aPrice);
}
void Find()
{
}
void Sell()
{
}
void ViewGenre(Store s)
{
char c;
Genre result;
do
c = GetAChar("Enter Genre - (F)iction, (M)ystery, (S)ci-Fi, or (C)omputer: ");
while ((c != 'F') && (c != 'M') && (c != 'S') && (c != 'C'));
switch (result)
{
case 'F': s.DisplayGenre(FICTION); break;
case 'M': s.DisplayGenre(MYSTERY); break;
case 'S': s.DisplayGenre(SCIFI); break;
case 'C': s.DisplayGenre(COMPUTER); break;
}
}
void Sort(Store s)
{
char c;
Genre result;
do
c = GetAChar("Enter Genre - (F)iction, (M)ystery, (S)ci-Fi, or (C)omputer: ");
while ((c != 'A') && (c != 'T'));
s.Sort(c);
}
void Intro(Store s)
{
double amount;
cout << "*** Welcome to Bookstore Inventory Manager ***\n"
<< "Please input the starting money in the cash register: ";
/* cin >> amount;
s.SetCashRegister(amount);*/
}
int main()
{
Store mainStore;// Create and initialize a Store.
Intro(mainStore);//Display intro & set Cash Regsiter
ShowMenu();// Display the menu.
/*mainStore.Insert("A Clockwork Orange", "Anthony Burgess", SCIFI, 30.25);
mainStore.Insert("X-Factor", "Anthony Burgess", SCIFI, 30.25);*/
char command;// menu command entered by user
do
{
command = GetCommand();// Retrieve a command.
switch (command)
{
case 'A': Add(mainStore); break;
case 'F': Find(); break;
case 'S': Sell(); break;
case 'D': mainStore.DisplayStore(); break;
case 'G': ViewGenre(mainStore); break;
case 'O': Sort(mainStore); break;
case 'M': ShowMenu(); break;
case 'X': break;
}
} while ((command != 'X'));
return 0;
}
Please, any and all help you can offer is amazing.
Thank you.
Welcome to the exciting world of C++!
Short answer: you're passing Store as a value. All your menu functions should take a Store& or Store* instead.
When you're passing Store as a value then an implicit copy is done (so the mainStore variable is never actually modified). When you return from the function the Store::~Store is called to clean up the copied data. This frees mainStore.bookList without changing the actual pointer value.
Further menu manipulation will corrupt memory and do many double frees.
HINT: If you're on linux you can run your program under valgrind and it will point out most simple memory errors.
Your Store contains dynamically-allocated data, but does not have an assignment operator. You have violated the Rule of Three.
I don't see the Store class being instantiated anywhere by a call to new Store() which means the booklist array has not been created but when the program exits and calls the destructor, it tries to remove the array that was never allocated and hence that's why i think you are getting this error. Either, modify the destructor to have a null check or instantiate the class by a call to the constructor. Your code shouldn't still be working anywhere you are trying to use a Store object.
Hope this helps
I am tasked with trying to create a histogram from a set of sample values that a user provides. I've created the part of the program that creates the array from sample value input, but now I must take a user input for the histogram. They give min value, max value, and number of bins. So, I'm assuming the number of bins specifies the size of the array for the histogram. But I'm stumped as to how I go to my other array and count how many values are in the specified range for a particular bin. I hope this makes sense. Here is my code for the program thus far:
#include <iostream>
using namespace std;
#define MAX_SAMPLES 100
#define MAX_BINS 20
#define DOUBLE_TOLERANCE 0.0000005
#define EXIT_VALUE -999
int promptUserAndGetChoice(); //function prototype for the menu
//for information describing sample set of data and functions that operated on //those data
class SamplingClass
{
private:
char charID; //the user enters an id for his sample set
int numbOfValues; // the number of good values the user enters
double sampleValues[MAX_SAMPLES]; //for the set of sample values.
//max is 100
public:
bool readFromKeyboard(); //prototype function
bool printToScreen();//protype function
SamplingClass(); //constructor
};
SamplingClass::SamplingClass() //initializing charID
{
charID = 0;
}
bool SamplingClass::readFromKeyboard()
{
int i = 0;
cout << "Enter character identifier for this sample:";
cin >> charID;
cout << "you entered " <<charID << "\n";
cout << "Enter all samples, then enter -999 to end:\n";
while (i < MAX_SAMPLES)
{
cin >> sampleValues[i];
if
(sampleValues[i] < EXIT_VALUE + DOUBLE_TOLERANCE && sampleValues[i] > EXIT_VALUE - DOUBLE_TOLERANCE)
{
break;
}//End if/else
i++;
}//End while
numbOfValues = i;
return true;
}
//this function checks whether charID is empty and then performs accordingly
bool SamplingClass::printToScreen()
{
if (numbOfValues == 0) ///either make a test for existance first or charID
{
cout << "ERROR: Can not print uninitialized sampling!\n";
return false;
}
else
{
cout << "Data stored for sampling with identifier " << charID << ":\n";
cout << "Total samples:" << numbOfValues << "\n";
cout << "Samples (5 samples per line):\n";
int i;
for(i=0; i<numbOfValues;i++)
{
cout << sampleValues[i] << " ";
if (((i+1) % 5) == 0)
{
cout << endl;
}
}
cout << endl;
return true;
}
}
class HistogramClass
{
private:
double minBinValue; //specified by user
double maxBinValue; // specified by user
int numbBins; //specified by user, max of 10
int histoBinCounts[MAX_BINS];
public:
bool setupHistogram(); //prototype function
bool addDataToHistogram(SamplingClass &sampling);//protype function
bool printHistogramCounts();
bool displayHistogram();
};
bool HistogramClass::setupHistogram()
{
cout << "Enter minimum value:";
cin >> minBinValue;
cout << "Enter maximum value:";
cin >> maxBinValue;
cout << "Enter number of bins:";
cin >> numbBins;
cout << "\n";
if (numbBins <= MAX_BINS)
{cin >> numbBins;}
else
cout << "Sorry, the maximum amount of bins allowed is 20. Try again!\n";
}
//function for the menu options that display to user
int promptUserAndGetChoice()
{
cout << "1. Enter a sample set of data values\n";
cout << "2. Print the contents of the current sample set\n";
cout << "3. Reset / Provide values for setting up a histogram\n";
cout << "4. Add the contents of current sample set to histogram\n";
cout << "5. Print bin counts contained in histogram\n";
cout << "6. View the histogram in graphical form\n";
cout << "0: Exit the program\n\n";
}
int main()
{
const int enter_option = 1;
const int printContents_option = 2;
const int reset_option = 3;
const int add_option = 4;
const int printBin_option = 5;
const int viewHist_option = 6;
const int exit_option = 7;
int menuChoice;
SamplingClass sampleSet;
HistogramClass histoSet;
do
{
promptUserAndGetChoice();
cout << "Your Choice: ";
cin >> menuChoice;
if (menuChoice == 1)
{
sampleSet.readFromKeyboard();
cout << "Last Operation Successful: YES\n\n";
}
else if (menuChoice == 2)
{
sampleSet.printToScreen();
}
else if (menuChoice == 3)
{
histoSet.setupHistogram();
}
}
while (menuChoice != 7);
return 0;
}
Each bin in a histograms is typically the same size. So when the user gives you the min, max and number of bins, you can compute the size, and therefore the range, of each bin. Each bin will be of size
bin_size = (max-min)/#_of_bins.
Now to figure out which bin a value goes into, compute
bin = ceil(value/bin_size)
(Or take the floor if you start numbering your bins at 0). And increment the count in this bin. Once you do this for all values, you can print out the count in each bin and this is your histogram.
Update: If min != 0, then the formula is:
bin = (int) (value-min)/bin_size
Using the cast here b/c codemesserupper can't use libs. bin here will be 0-indexed.
If you know the min and max, then any particular value x should be considered to fall into the array at index:
(x - min) / (max - min) * #bins
This will span the range 0..#bins inclusive, so just round down from #bins to #bins-1 when necessary.
EDIT: to be more explicit, and ignoring the object boundaries, the basic approach is to 0 the histoBinCounts then:
for (int i = 0; i < numbOfValues; ++i)
{
double x = sampleValues[i];
int bin = (x - minBinValue) / (maxBinValue - minBinValue) * numbBins;
if (bin >= 0 && bin < numbBins)
++histoBinCounts[bin];
}