Inserting Values of Array to Ordered Linked List C++ - c++

Background
Creating a dice game where the dice roll value should be stored in a Linked List.
Question
How should an implementation of Linked List be completed in C++? '
Example (What I have tried using struct instead of class)
#include <time.h>
#include <stdlib.h>
#include <stdio.h>
#include <iostream>
struct Score {
int d1;
int d2;
int total;
int totals[13];
int value;
struct Score * next;
}
score_dice1, score_dice2, score_total, score_totals;
struct Score * ordered_insert(struct Score * , struct Score * );
int dice = 2;
void Randomize() {
srand((unsigned) time(NULL));
}
int Random(int Max) {
return (rand() % Max) + 1;
}
int main(int argc, char * argv[]) {
struct Score * myList = NULL;
if (argc == 2) {
int dice_rolls;
dice_rolls = atoi(argv[1]);
Randomize();
for (dice = 2; dice <= 12; dice++)
score_totals.totals[dice] = 0;
for (dice = 0; dice < dice_rolls; dice++) {
score_dice1.d1 = Random(6);
score_dice2.d2 = Random(6);
score_total.total = score_dice1.d1 + score_dice2.d2;
score_totals.totals[score_total.total]++;
}
for (dice = 1; dice <= 13; dice++) {
printf("%i %i\n\r", dice, score_totals.totals[dice]);
}
} else {
std::cout << "How many times should we roll the dice?" << '\n' <<
"One number please" << '\n';
}
return 0;
}

You probably want to use the STL, and include the std::list class. You should look at the methods for that class. I will show you how using the std::vector class.
Suppose you want to place the following into the list,
struct roll_t {
int dice1; //value of dice1
int dice2; //value of dice2
int total; //total of dice1+dice2
roll_t() dice1(0), dice2(0), total(0) { }
roll_t(int d1, int d2) : dice1(d1), dice2(d2), total(d1+d2) { };
};
Here is a C++ list reference
Here is an example with explanation
But, let me also add an example here,
#include <vector>
using namespace std;
int main(int argc, char* argv[])
{
vector<roll_t> dv;
roll_t rolls[13+1];
//suppose you have initialized totals[] here...
for( ndx=1; ndx<=12; ++ndx ) {
rolls[ndx] = roll_t.new(random(6),random(6));
}
//move totals to vector (convert to list left as exercise for poster)
int ndx;
for( ndx=1; ndx<=12; ++ndx ) {
dv.push_back(rolls[ndx]);
}
//traverse vector (convert to list, you will need iterator)
cout << "Loop by index:" << endl;
for(ndx=0; ndx < dv.size(); dv++)
{
cout << "["<<ndx<<"]"
<< dv[ndx].dice1 <<','<< dv[ndx].dice2 <<','<< dv[ndx].total << endl;
}
}
The above uses the STL, but maybe this question is for a class? And you need to roll your own linked list? I have linked to some stackoverflow answers,
I built one of those,
Trying to make linkedlist in C
Here is a description of single-linked list,
Singly-list insert to end of list
Here is a basic C++ dice game,
Basic C++ Dice game
Here is an explanation of how to sort a linked list by moving pointers,
Trying to Sort a Linked List only by Manipulating Pointers
Those should help.

Answer
Use a class to create the Linked List logic.
Example
linklist.h
#pragma once
#ifndef LINKLIST_H
#define LINKLIST_H
#include <iostream>
using namespace std;
class linklist {
private:
struct node {
int data;
node * link;
}* p;
public:
linklist();
void append(int num);
void add_as_first(int num);
void addafter(int c, int num);
void del(int num);
void display();
int count();
~linklist();
};
linklist::linklist() {
p = NULL;
}
void linklist::append(int num) {
node * q, * t;
if (p == NULL) {
p = new node;
p -> data = num;
p -> link = NULL;
} else {
q = p;
while (q -> link != NULL)
q = q -> link;
t = new node;
t -> data = num;
t -> link = NULL;
q -> link = t;
}
}
void linklist::add_as_first(int num) {
node * q;
q = new node;
q -> data = num;
q -> link = p;
p = q;
}
void linklist::addafter(int c, int num) {
node * q, * t;
int i;
for (i = 0, q = p; i < c; i++) {
q = q -> link;
if (q == NULL) {
cout << "\nThere are less than " << c << " elements.";
return;
}
}
t = new node;
t -> data = num;
t -> link = q -> link;
q -> link = t;
}
void linklist::del(int num) {
node * q, * r;
q = p;
if (q -> data == num) {
p = q -> link;
delete q;
return;
}
r = q;
while (q != NULL) {
if (q -> data == num)
{
r -> link = q -> link;
delete q;
return;
}
r = q;
q = q -> link;
}
cout << "\nElement " << num << " not Found.";
}
void linklist::display() {
node * q;
cout << endl;
for (q = p; q != NULL; q = q -> link)
cout << endl << q -> data;
}
int linklist::count() {
node * q;
int c = 0;
for (q = p; q != NULL; q = q -> link)
c++;
return c;
}
linklist::~linklist() {
node * q;
if (p == NULL)
return;
while (p != NULL) {
q = p -> link;
delete p;
p = q;
}
}
#endif
main.cc
#include <time.h>
#include <stdlib.h>
#include <stdio.h>
#include <iostream>
#include <list>
#include <vector>
#include "linklist.h"
struct score {
int d1;
int d2;
int total;
int totals[13];
}
score_dice1, score_dice2, score_total, score_totals;
int dice = 2;
void Randomize() {
srand((unsigned) time(NULL));
}
int Random(int Max) {
return (rand() % Max) + 1;
}
int main(int argc, char * argv[]) {
linklist ll;
if (argc == 2) {
int dice_rolls;
dice_rolls = atoi(argv[1]);
Randomize();
for (dice = 2; dice <= 12; dice++)
score_totals.totals[dice] = 0;
for (dice = 0; dice < dice_rolls; dice++) {
score_dice1.d1 = Random(6);
score_dice2.d2 = Random(6);
score_total.total = score_dice1.d1 + score_dice2.d2;
score_totals.totals[score_total.total]++;
}
for (dice = 1; dice <= 13; dice++) {
ll.append(score_totals.totals[dice]);
std::cout << ll.count() << '\n';
ll.display();
}
} else {
std::cout << "How many times should we roll the dice?" << '\n' <<
"One number please" << '\n';
}
return 0;
}

Related

Exception thrown: write access violation

I am trying to implement a list structure, but when I wrote the insert() function which inserts an element in a specific position in the list, I get an error Exception thrown: write access violation.
pl was 0x34812B3A.
I tried alot to fix it but I really can't. I used try..throw..catch and still didn't get it, so what should I do.
This is my code:
List.h
#pragma once
#define MAXLIST 100
typedef struct List {
int size;
int entry[MAXLIST];
}list;
void createl(list*);
int ListEmpty(list*);
int ListFull(list*);
int sizel(list*);
void destroyl(list*);
void insert(int, int, list*);
void deletei(int* , int, list*);
void traversel(list*, void (*)(int));
void retrieve(int*, int, list*);
void replace(int, int, list*);
//int access(int , list*);
and this is the implementation (List.cpp)
#include <iostream>
#include "List.h"
using namespace std;
void createl(list* pl) {
pl->size = 0;
}
int isEmpty(list* pl) {
return !(pl->size);
}
int isFull(list* pl) {
return (pl->size == MAXLIST);
}
int sizel(list* pl) {
return pl->size;
}
void destroyl(list* pl) {
pl->size = 0;
}
void insert(int e, int p, list* pl) { //insert element e in the postion p in the list
for (int i = pl->size -1; i >= p; i--) {
pl->entry[i+1] = pl->entry[i];
}
pl->entry[p] = e;
pl->size++;
}
void deletei(int* pe, int p, list* pl) {
*pe = pl->entry[p];
for (int i = p + 1; i < pl->size; ++i) {
pl->entry[i-1] = pl->entry[i];
}
pl->size--;
}
void traversel(list* pl, void (*pf)(int e)) {
for (int i = 0; i < pl->size; ++i) {
(*pf)(pl->entry[i]);
}
}
void retrieve(int* pe, int p, list* pl) {
*pe = pl->entry[p];
}
void replace(int e, int p, list* pl) {
pl->entry[p] = e;
}
/*int access(int p, list* pl) {
return pl->entry[p];
}*/
I get the error here in function insert()
pl->entry[p] = e;
and this is a program to just check if my code works.
#include <iostream>
#include "List.h"
using namespace std;
void display(int e) {
cout << e << "\n";
}
int main() {
list l;
list* ptl = &l;
int t;
cout << "Put 5 elements:\n";
for (int i = 0; i < 5; ++i) {
cin >> t;
insert(t, sizel(ptl), ptl);
}
cout << "The list looks like a stack\n\n";
traversel(ptl, display);
cout << "The size of the list is: " << sizel(ptl) << endl;
insert(9, 2, ptl);
cout << "The size of the list is: " << sizel(ptl) << endl;
int temp;
deletei(&temp, 2, ptl);
cout << temp <<endl ;
traversel(ptl, display);
cout << "The size of the list is: " << sizel(&l) << endl;
int t2;
retrieve(&t2, 2, ptl);
cout << t2 << endl;
replace(4, 1, ptl);
traversel(ptl, display);
destroyl(ptl);
cout << "The size of the list is: " << sizel(ptl) << endl;
return 0;
}
Thank you for your time and helping me.
You used ptl, which points at l, without initializing l.
Add initialization like this:
int main() {
list l;
list* ptl = &l;
int t;
createl(ptl); // add initialization
cout << "Put 5 elements:\n";
for (int i = 0; i < 5; ++i) {
cin >> t;
insert(t, sizel(ptl), ptl);
}

I Cannot Embed My Header File to Main.cpp

I have a homework which is done with C++. I coded it using a Main.cpp and a header file (datastruct.h). Homework was done, compiled and run successfully; but submission rules allow me to use just one main.cpp. When I tried to include my code in header to main.cpp I get:
[main] C:\cygnus\cygwin-b20\H-i586-cygwin32\bin\g++.exe 1000 (0) handle_exceptions: Exception: STATUS_ACCESS_VIOLATION
[main] g++ 1000 (0) handle_exceptions: Dumping stack trace to g++.exe.core
Note that: My question is not just about this error, it is about I get this error only I embed my header code to main.cpp. When they are separated, it works fine.
Here is my main.cpp when header codes were not included:
#include <iostream>
#include <fstream>
#include "datastruct.h"
using namespace std;
int main(int argc, char *argv[])
{
Game myGame;
myGame.initializer(argv[1]);
cout << myGame.gamePlay();
myGame.cleaner();
return 0;
}
And here is "datastruct.h":
#ifndef DATASTRUCT_H
#define DATASTRUCT_H
#include <iostream>
#include <fstream>
using namespace std;
int abs(int k) {
if(k < 0) k = -k;
return k;
}
struct Card {
int value;
Card* prev;
};
struct Deck {
Card* top ;
int cardNum;
void addCard(int xd);
int dropCard();
void create();
void clear();
void print();
};
void Deck::clear(/* arguments */) {
Card *p;
while(top)
{
p = top;
top = top -> prev;
delete p;
}
}
int Deck::dropCard(/* arguments */) {
Card* cardPtr;
int returnVal = top -> value;
cardPtr = top;
top = top -> prev;
delete cardPtr;
cardNum--;
return returnVal;
}
void Deck::create() {
cardNum = 0;
top = NULL;
}
void Deck::addCard(int xd) {
Card* newCard;
newCard = new struct Card;
newCard -> value = xd;
newCard -> prev = top;
top = newCard;
cardNum++;
}
struct Game {
Deck* p1;
Deck* p2;
Deck* table;
Deck* bin;
void initializer(char* filename);
void cleaner();
void gamePrint();
void p1gives();
void p2gives();
int gamePlay();
};
int Game::gamePlay()
{
int cardTaken;
while (true)
{
if((p1->cardNum ==0) || (p2->cardNum ==0) || (table->cardNum ==0)) break;
cardTaken = table->dropCard();
if (cardTaken < 0) {
for (int i = 0; i < abs(cardTaken); i++) {
if(p1->top == NULL) break;
p1gives();
}
} else {
for (int i = 0; i < cardTaken; i++) {
if(p2->top == NULL) break;
p2gives();
}
}
if((p1->cardNum ==0) || (p2->cardNum ==0) || (table->cardNum ==0)) break;
cardTaken = table->dropCard();
if (cardTaken < 0) {
for (int i = 0; i < abs(cardTaken); i++) {
if((p1->top == NULL) || (p2->top == NULL)) break;
p2gives();
}
} else {
for (int i = 0; i < cardTaken; i++) {
if((p1->top == NULL) || (p2->top == NULL)) break;
p1gives();
}
}
}
return (bin -> cardNum);
}
void Game::p1gives()
{
if(p2 -> top == NULL)
p2 -> addCard(p1 -> dropCard());
else if (p1 -> top -> value > p2 -> top -> value)
p2 -> addCard(p1 -> dropCard());
else if (p1 -> top -> value <= p2 -> top -> value)
bin -> addCard(p1 -> dropCard());
}
void Game::p2gives()
{
if (p1 -> top == NULL)
p1 -> addCard(p2 -> dropCard());
else if(p2 -> top -> value > p1 -> top -> value)
p1 -> addCard(p2 -> dropCard());
else if(p2 -> top -> value <= p1 -> top -> value)
bin -> addCard(p2 -> dropCard());
}
void Game::cleaner()
{
p1 -> clear();
p2 -> clear();
table -> clear();
bin -> clear();
delete p1;
delete p2;
delete table;
delete bin;
}
void Game::initializer(char* filename)
{
ifstream myFile(filename);
int tableDeckCount, playerDeckCount;
myFile >> tableDeckCount;
myFile >> playerDeckCount;
p1 = new struct Deck;
p1 -> create();
p2 = new struct Deck;
p2 -> create();
table = new struct Deck;
table -> create();
bin = new struct Deck;
bin -> create();
for (int i = 0; i < tableDeckCount; i++) {
int x;
myFile >> x;
table -> addCard(x);
}
for (int i = 0; i < playerDeckCount; i++) {
int x;
myFile >> x;
p1 -> addCard(x);
}
for (int i = 0; i < playerDeckCount; i++) {
int x;
myFile >> x;
p2 -> addCard(x);
}
}
void Deck::print(/* arguments */) {
Card* traverse;
traverse = top;
while (traverse) {
cout << traverse -> value << " , " ;
traverse = traverse -> prev;
}
cout << endl;
}
void Game::gamePrint()
{
cout << "P1:" << endl;
p1 -> print();
cout << "P2:" << endl;
p2 -> print();
cout << "TABLE:" << endl;
table -> print();
cout << "BIN:" << endl;
bin -> print();
}
#endif
I need to include header into main.cpp but when I copy codes I get error. Can someone help me?
Expected work example:
>g++ -std=c++0x -Wall -Wextra -Werror main.cpp -o cardgame
>./cardgame example.game
1
example.game file:
1 3
-2
6
7
8
1
5
4
Run the compilation in elevated privileges on Windows? (right-click run as administrator) /edit. Right-click on sh.exe for cygwin and go to compatibility and check the box "run as administrator")
also, for reference to those who negatively voted: https://developer.qualcomm.com/forum/qdn-forums/mobile-technologies/multimedia-optimization-hexagon-sdk/toolsinstallation/27100

Printing from Trie

I have built a trie in C++ designed to hold words of sentences. Each sentence will have a weight which determines the order in which they should be output. I have several recursive functions that call other recursive functions, and the dilemma I am facing is that I want to print my list only once.
Basically my get function calls the printFromNode function which creates the vector of pairs p that I want to sort and print. If someone could point me in the right direction in how to do that it would be much appreciated.
Code:
Trie.cpp:
//#include "Trie.h"
#include <iostream>
#include <cstdlib>
#include <cstring>
#include <string>
#include <vector>
#include <sstream>
#include <stack>
using namespace std;
class Node
{
private:
string word = "";
bool endOfSentence = false;
int weight = -1;
public:
vector<Node> children = {};
Node() {
this->setWord("");
}
Node(string s){
this->setWord(s);
}
string getWord(){
return this->word;
}
void setWord(string s) {
this->word = s;
}
void setEOS(){
this->endOfSentence = true;
}
void setWeight(int weight){
this->weight = weight;
}
int getWeight() {
return this->weight;
}
};
class Trie
{
public:
Node root;
void add(vector<string> phrase, int weight, Node* n){
Node* current = n;
int w = weight;
int found = -1;
for (int i = 0; i < current->children.size(); i++) {
if (phrase[0] == current->children[i].getWord()) {
found = i;
}
}
if (found > -1) {
current = &current->children[found];
phrase.erase(phrase.begin());
add(phrase, w, current);
}
else {
addPhrase(phrase, w, current);
}
}
void addPhrase(vector<string> phrase, int weight, Node* n) {
Node* current = n;
for (int i = 0; i < phrase.size(); i++) {
Node temp = *new Node(phrase[i]);
current->children.push_back(temp);
current = &current->children.back();
if (i == phrase.size() - 1) {
current->setEOS();
current->setWeight(weight);
}
}
}
void get(vector<string> search) {
Node* current = &this->root;
get(search, current);
}
void get(vector<string> search, Node* n) {
Node* current = n;
int found = -1;
//test search size
if (search.size() == 0) {
cout << "Please enter a valid search" << endl;
}
for (int i = 0; i < current->children.size(); i++) {
if (search[0] == current->children[i].getWord()) {
found = i;
}
}
if (found > -1 && search.size() == 1) {
current = &current->children[found];
printFromNode(*current);
maxNode(*current);
}
else if (found > -1 && search.size() != 1) {
current = &current->children[found];
search.erase(search.begin());
get(search, current);
}
else {
cout << "Not Found" << endl;
}
}
void printOutput(vector<pair<int,string>> p){
sort(p.begin(), p.end());
cout << p.size() << endl;
for (int i = 0; i < p.size(); i++) {
cout << p[i].second << " " << endl;
}
}
void printFromNode(Node n) {
vector<string> phrase = {};
vector <pair < int, string>> final = {};
printFromNode(n,phrase,final);
}
void printFromNode(Node n, vector<string> &v, vector<pair<int,string>> &p) {
string output;
if (n.getWord() == "") {
return;
}
for (int i = 0; i < n.children.size(); i++) {
if (n.children[i].getWeight() > 0) {
for (int i = 0; i < v.size(); i++)
{
output.append(v[i] + " ");
}
output.append(n.children[i].getWord());
p.push_back(make_pair(n.children[i].getWeight(), output));
}
v.push_back(n.children[i].getWord());
printFromNode(n.children[i], v, p);
v.pop_back();
sort(p.begin(), p.end());
}
return;
}
void maxNode(Node n) {
int max = 0;
int index = 0;
int temp = 0;
for (int i = 0; i < n.children.size(); i++) {
temp = n.children[i].children.size();
if (temp > max) {
max = temp;
index = i;
}
}
cout << n.children[index].getWord() << " " << max << endl;
}
};
Main.cpp:
#include "Trie.cpp"
#include <iostream>
#include <sstream>
#include <string>
#include <vector>
using namespace std;
int main(int argc, char* argv[]) {
// Initialize trie up here
Trie myTrie = *new Trie();
// parse input lines until I find newline
for(string line; getline(cin, line) && line.compare(""); ) {
stringstream ss(line);
string string_weight;
ss >> string_weight;
int weight = stoi(string_weight);
// I am just going to put these words into a vector
// you probably want to put them in your trie
vector<string> phrase = {};
for(string word; ss >> word;) {
phrase.push_back(word);
}
myTrie.add(phrase, weight, &myTrie.root);
vector<string> ans = {};
}
// parse query line
string query;
getline(cin, query);
stringstream ss(query);
vector<string> search = {};
for (string query; ss >> query;) {
search.push_back(query);
}
myTrie.get(search);
return 0;
}
You can remove recursive methods, and doing something like the following:
#include <algorithm>
#include <iostream>
#include <map>
#include <string>
#include <vector>
#include <set>
class Node
{
public:
bool endOfSentence = false;
std::set<int> weights;
std::map<std::string, Node> children;
Node() = default;
const Node* get(const std::string& word) const
{
auto it = children.find(word);
if (it == children.end()) {
return nullptr;
}
return &it->second;
}
auto find_by_weight(int weight) const
{
return std::find_if(children.begin(),
children.end(),
[=](const auto& p){ return p.second.weights.count(weight);});
}
};
class Trie
{
Node root;
public:
void add(int weight, const std::vector<std::string>& phrase)
{
Node* node = &root;
for (const auto& word : phrase) {
node->weights.insert(weight);
node = &node->children[word];
}
node->weights.insert(weight);
node->endOfSentence = true;
}
bool contains(const std::vector<std::string>& phrase) const
{
const Node* node = &root;
for (const auto& word : phrase) {
node = node->get(word);
if (node == nullptr) {
return false;
}
}
return node->endOfSentence;
}
void print(int weight) const
{
const Node* node = &root;
const char* sep = "";
while (node) {
const auto it = node->find_by_weight(weight);
if (it == node->children.end()) {
break;
}
std::cout << sep << it->first;
sep = " ";
node = &it->second;
}
std::cout << std::endl;
}
void print_all() const
{
for (int i : root.weights) {
print(i);
}
}
};
And usage/Test:
int main(int argc, char* argv[]) {
const std::vector<std::vector<std::string>> sentences = {
{"My", "name", "is", "John"},
{"My", "house", "is", "small"},
{"Hello", "world"},
{"Hello", "world", "!"}
};
Trie trie;
int i = 0;
for (const auto& sentence : sentences) {
trie.add(i, sentence);
++i;
}
const std::vector<std::vector<std::string>> queries = {
{"My", "name", "is", "John"},
{"My", "house"},
{"Hello", "world"}
};
for (const auto& query : queries) {
std::cout << trie.contains(query) << std::endl;
}
trie.print_all();
}
Demo

How can i iterator through all possible nodes and determine if it is Eulerian Circuit?

I can't seem to iterate through all the nodes. It goes through only 1 or two nodes and fails to return true for any case. I want the program to iterator through the node multiple times to get all possible outcome, but still be Eulerian circuit. This is just a small example. To determine if it is Eulerian Circuit, it must pass through the edge only once. Whenever i tried the recursive function DFSUtil, it will stop at the first node or the 2nd node.
Example:
start = A
End = C
A connect to B
A connect to C
B connect to A
B connect to C
C connect to B
Result: 2 path
A -> B -> C -> B -> A -> C
A -> B -> A -> C -> B -> C
#include <iostream>
#include <string>
#include <string.h>
#include <sstream>
#include <stdio.h>
#include <stack>
#include <vector>
using namespace std;
unsigned int V;
class node
{
public:
string Enzyme;
vector<node> connection;
node(string Enzyme)
{
this->Enzyme = Enzyme;
}
bool isEulerCircuit();
bool isConnected();
string DFSUtil(unsigned int v,bool visited[]);
void add_edge(node &n)
{
connection.push_back(n);
cout << Enzyme << " connected to " << n.Enzyme << endl;
}
};
string node::DFSUtil(unsigned int v,bool visited[])
{
visited[v] = true;
vector<node>::iterator it;
string res;
for(it = connection.begin(); it != connection.end(); it++)
{
cout << (*it).Enzyme << endl;
if(!visited[v])
{
res+= (*it).Enzyme;
DFSUtil(v,visited);
}
}
return res;
}
bool node::isEulerCircuit()
{
if (isConnected() == false)
{
return false;
}
return true;
}
bool node::isConnected()
{
bool visited[V];
for(int i = 0; i < V; i++)
{
visited[i] = false;
}
int n=3;
DFSUtil(n,visited);
for (int i = 0; i < V; i++)
{
if (visited[i] == false)
{
return false;
}
}
return true;
}
int main()
{
vector<node> nod;
string A = "A";
string B = "B";
string C = "C";
nod.push_back(A);
nod.push_back(B);
nod.push_back(C);
for(int i = 0; i < nod.size(); i++)
{
V = i;
}
cout << endl;
nod[0].add_edge(nod[1]);
nod[0].add_edge(nod[2]);
nod[1].add_edge(nod[0]);
nod[1].add_edge(nod[2]);
nod[2].add_edge(nod[1]);
if(nod[0].isEulerCircuit())
{
cout << "HI" << endl;
}
else
{
cout << "BYE" << endl;
}
return 0;
}

C++ none of the 3 overloads could convert all the argument types line 39 1

So after coding this I got an error : C++ none of the 3 overloads could convert all the argument types line 39 1 in w5.cpp
do you know where is the problem? and could you help me to fix it? I actually dont know why it is showing this because I got the default constructor for this code.
//w5.h
#define MAX_LINE_LENGTH 256
#define MAX_PURCHASES 5
// w5.cpp
#include <iostream>
#include <cstring>
#include "w5.h"
#include "CreditStatement.h"
using namespace std;
void sort(CreditStatement* statement, int n);
int main()
{
double price;
int n = 0;
CreditStatement statement[MAX_PURCHASES];
cout << "Credit Statement Processor\n";
cout << "==========================\n";
do
{
cout << "Item price (0 to quit): ";
cin >> price;
if (cin.fail() || (cin.get() != '\n'))
{
cin.ignore(2000, '\n');
cerr << "Bad character. Try again." << endl;
cin.clear();
}
else if ((int)price != 0)
{
cout << "Statement item: ";
char item[MAX_LINE_LENGTH];
cin.getline(item, MAX_LINE_LENGTH);
if (strlen(item) > 0)
{
statement[n] = CreditStatement(item, price);
n++;
}
}
} while ((int)price != 0 && n < MAX_PURCHASES);
cout << endl;
sort(statement, n);
cout << " Credit Statement\n\n";
cout << " Item Price\n";
cout << "----------------------------------\n";
for (int i = 0; i < n; i++)
{
statement[i].display();
}
cout << endl;
return 0;
}
// sort sorts the elements of Credit Card Statement[n] in ascending order
//
void sort(CreditStatement* s, int n)
{
int i, j;
CreditStatement temp;
for (i = n - 1; i > 0; i--)
{
for (j = 0; j < i; j++)
{
if (s[j].isGreaterThan(s[j + 1]))
{
temp = s[j];
s[j] = s[j + 1];
s[j + 1] = temp;
}
}
}
}
//CreditStatement.h
class CreditStatement{
bool _valid;
double* _price;
char* _item;
public:
CreditStatement();
CreditStatement(char*, double*);
CreditStatement(const CreditStatement&);
CreditStatement& operator=(const CreditStatement&);
//output
void display() const;
//mutators
bool isGreaterThan(const CreditStatement&) const;
};
//CreditStatement.cpp
#include <iostream>
#include <new>
#include "CreditStatement.h"
using namespace std;
void CreditStatement::display() const{
cout << " Something" << _price << _item;
}
bool CreditStatement::isGreaterThan(const CreditStatement&) const{
return _valid;
}
CreditStatement::CreditStatement(){
_item = NULL;
_price = NULL;
}
CreditStatement::CreditStatement(char* iP, double* pP){
_price = NULL;
_item = NULL;
if (pP != NULL){
int sizepP = sizeof(pP) / sizeof(pP[0]);
_price = new (nothrow) double[sizepP];
if (_price){
for (int i = 0; i <sizepP; i++){
_price[i] = pP[i];
};
}
if (iP != NULL){
int sizeiP = sizeof(iP) / sizeof(iP[0]);
_item = new (nothrow) char [sizeiP];
if (_item){
for (int i = 0; i < sizeiP; i++){
_item[i] = iP[i];
};
}
}
}
}
CreditStatement::CreditStatement(const CreditStatement& otherCS){
*this = CreditStatement(otherCS._item, otherCS._price);
}
CreditStatement& CreditStatement::operator=(const CreditStatement& otherCS){
if (this != &otherCS)
{
if (_item){
delete[] _item;
_item = NULL;
}
if (_price){
delete[] _price;
_price = NULL;
}
else{
if (otherCS._price != NULL){
int sizepP = sizeof(otherCS._price) / sizeof(otherCS._price[0]);
_price = new (nothrow) double[sizepP];
if (_price){
for (int i = 0; i < sizepP; i++){
_price[i] = otherCS._price[i];
};
}
if (otherCS._item != NULL){
int sizeiP = sizeof(otherCS._item) / sizeof(otherCS._item[0]);
_item = new (nothrow) char[sizeiP];
if (_item){
for (int i = 0; i < sizeiP; i++){
_item[i] = otherCS._item[i];
};
}
}
}
}
}
return *this;
}
I also got this error
"no instance of constructor "CreditStatement::CreditStatement" matches the argument list
argument types are: (char [256], double) c:*\Project1\w5.cpp 38 20.
I think the problem is your call statement[n] = CreditStatement(item, price);
Here, price is a double, but there's a constructor CreditStatement(char*, double*); but none with signature CreditStatement(char*, double);
You might want to fix that.