Here is a program with my Stack class and some another functions.
ReadTheFile() - reads numbers, which are stored in num_file.txt, and returns a vector with those numbers.
IntervalCheck() - adds the numbers of the specific range from input vector and returns a vector with those numbers only.
VecToMyStack() - adds numbers from a vector to a stack.
#include <iostream>
#include <string>
#include <vector>
#include <fstream>
#define STACK_EMPTY -1
#define OUT_OF_STACK -2
using namespace std;
template <class T>
class Stack {
private:
struct Node{
T element;
Node *prevElement;
};
size_t NumberOfElements;
Node *tempAdr;
Node *topElement;
Node *newElement;
Node *erasedElement;
public:
Stack(){
topElement = new Node;
topElement->prevElement = nullptr;
NumberOfElements = 0;
}
~Stack(){
cout << endl << "I'm a destructor";
while(NumberOfElements !=0 ){
tempAdr = topElement->prevElement;
delete topElement;
topElement = tempAdr;
NumberOfElements--;
}
delete topElement;
}
void push(T input_element){
tempAdr = topElement;
topElement = new Node;
topElement->element = input_element;
topElement->prevElement = tempAdr;
NumberOfElements++;
}
void pop(){
if (NumberOfElements == 0) throw STACK_EMPTY;
else {
tempAdr = topElement->prevElement;
delete topElement;
topElement = tempAdr;
NumberOfElements--;
}
}
T top(){
return NumberOfElements != 0 ? topElement->element : throw STACK_EMPTY;
}
void insert(size_t position, T input_element){
if (position >= NumberOfElements) throw OUT_OF_STACK;
else {
tempAdr = topElement;
for (size_t i = 0; i < position; i++){
tempAdr = tempAdr->prevElement;
}
newElement = new Node;
newElement->element = input_element;
newElement->prevElement = tempAdr->prevElement;
tempAdr->prevElement = newElement;
NumberOfElements++;
}
}
void erase(size_t position){
if (position >= (NumberOfElements-1)) throw OUT_OF_STACK;
else{
tempAdr = topElement;
for (size_t i = 0; i < position; i++){
tempAdr = tempAdr->prevElement;
}
erasedElement = tempAdr->prevElement;
tempAdr->prevElement = tempAdr->prevElement->prevElement;
delete erasedElement;
NumberOfElements--;
}
}
void print(){
if (NumberOfElements != 0){
tempAdr = topElement;
for (size_t i = 0; i < NumberOfElements; i++){
cout << tempAdr->element << " ";
tempAdr = tempAdr->prevElement;
}
}
}
size_t size() { return NumberOfElements; }
};
vector<int> ReadTheFile() {
vector<int> vec_from_file;
int buffer;
ifstream basefile;
basefile.open("num_file.txt", ios::in);
if (basefile.is_open()) {
do {
if (basefile >> buffer)
vec_from_file.push_back(buffer);
else {
basefile.clear();
basefile.ignore(1, ' ');
}
} while (!basefile.eof());
basefile.close();
}
else cout << "Unable to open file" << endl;
return vec_from_file;
}
vector<int> IntervalCheck(vector<int> vec_for_check){
vector<int> out_vec;
if (vec_for_check.empty()) cout << "There is nothing to check";
else {
int begin_int, end_int;
do {
cin.clear();
cin.sync();
cout << "Input the first and the last value of the interval: ";
cin >> begin_int >> end_int;
} while (cin.fail());
for (auto &k : vec_for_check)
if (k > begin_int && k < end_int)
out_vec.push_back(k);
}
return out_vec;
}
Stack<int> VecToMyStack(vector<int> input_vec){
Stack<int> output_st;
if (input_vec.empty()) {
cout << "the end";
}
else {
for (auto &k : input_vec){
output_st.push(k);
}
}
return output_st;
}
int main(){
int choice = 0;
do {
cin.clear();
cin.sync();
VecToMyStack(IntervalCheck(ReadTheFile())).print();
cout << "Would you like to measure another interval? 1-yes 2-no";
cin >> choice;
} while (choice == 1);
system("pause");
return 0;
}
The whole program should push numbers from the file to a stack, and print this stack, using the print() method of the class. For example, if there is a num_file.txt with
0 1 2 3 4 5 6 7 8 9 10
inside, the program is expected to work in that way:
Input the first and the last value of the interval: 0 10 /* zero and
ten are inputed by the user*/
1 2 3 4 5 6 7 8 9
Would you like to measure another interval? 1-yes 2-no
But when the VecToMyStack(IntervalCheck(ReadTheFile())).print(); line is executed, I'm getting
Access violation reading location 0xFEEEFEEE.
exception. It seemes like the destructor of my Stack class is running before the print()function. Why does that happen? Is there something special what I should add to my Stack class or to VecToMyStack() function?
Finally, after a couple of hours of research, I've got that missing peace of code:
Stack(const Stack &object){
tempAdr = object.topElement;
T * tempMas=new T[object.NumberOfElements];
for (size_t i = 0; i < object.NumberOfElements; i++){
tempMas[i] = tempAdr->element;
tempAdr = tempAdr->prevElement;
}
topElement = new Node;
topElement->prevElement = nullptr;
NumberOfElements = 0;
for (int i = object.NumberOfElements - 1; i >= 0; i--){
push(tempMas[i]);
}
delete[] tempMas;
}
I know that my Stack class is still uncomplete without the overloaded assignment operator, but at least my code runs fine.
Related
I am trying to make program that get infix to postfix but when I entered +- in the infix equation
the output should be +- but I find that the output is ++ and if infix is -+ the output is --
it have been a week since I started to solve that problem
#include <iostream>
#include <string>
using namespace std;
//classes
class arr
{
private:
char *items;
int size;
int length;
public:
//default constructor
arr()
{
items = new char[100];
size = 100;
length = 0;
}
//constructor with parameters
arr(int arraySize)
{
items = new char[arraySize];
size = arraySize;
length = 0;
}
//check if array is empty
bool is_empty()
{
return length == 0 ? true : false;
}
//check if array full
bool is_full()
{
return length >= size - 1 ? true : false;
}
//returns array length
int getLength()
{
return length;
}
//return array size
int getSize()
{
return size;
}
//get array address
char *getAddress()
{
return &items[0];
}
//fill number of items in array based on elementNum
void fill(int elementNum)
{
char ch;
cout << "Enter characters you want to add\n";
if (elementNum > size - 1)
{
cout << "can't use elements number largger than " << size - 1;
return;
}
for (int i = 0; i < elementNum; i++)
{
cin >> ch;
insert(i, ch);
}
}
//display all elements in the array
void display()
{
if (is_empty())
{
cout << "there are no data /n";
return;
}
cout << "Array items are :\n";
for (int i = 0; i < length; i++)
{
cout << items[i] << "\t";
}
cout << endl;
}
void append(char ch)
{
insert(length, ch);
}
void insert(int index, char newItem)
{
if (is_full() || length<index || length + 1 == size)
{
cout << "\nSorry array is full\ncan't append letter more\n";
return;
}
else {
for (int i = length; i >= index; i--)
{
items[i + 1] = items[i];
}
items[index] = newItem;
length++;
}
}
int search(char ch)
{
if (!is_empty())
for (int i = 1; i <= length; i++)
{
if (items[i] == ch)
return i;
}
return 0;
}
void del(int index)
{
if (is_empty() || length<index) {
cout << "sorry can't delete item which is doesn't exist";
return;
}
for (int i = index; i < length; i++)
{
items[i] = items[i + 1];
}
length--;
}
void changeSize(int newSize)
{
if (newSize <= length - 1)
{
cout << "can't change size because the new size is small";
return;
}
char *tempItems = new char[newSize];
size = newSize;
for (int i = 0; i < length; i++)
{
tempItems[i] = items[i];
}
items = tempItems;
tempItems = NULL;
}
//merge two arrays
void merge(arr a)
{
this->size = this->size + a.getSize();
for (int i = 0; i < a.getLength(); i++)
{
items[i + length] = a.getAddress()[i];
}
length = this->length + a.getLength();
}
};
class stackUsingArray {
private:
int top;
arr a;
public:
stackUsingArray()
{
top = -1;
}
stackUsingArray(int stackSize)
{
a.changeSize(stackSize);
top = -1;
}
bool is_empty()
{
return(top == -1);
}
bool is_full()
{
return(a.is_full());
}
void push(char ch)
{
top++;
a.append(ch);
}
char pop()
{
if (is_empty())
{
cout << "sorry the stack is empty";
}
else
return a.getAddress()[top--];
}
int peekTop() {
return top;
}
void display()
{
//first way of display
for (int i = top; i >= 0; i--)
{
cout << a.getAddress()[i];
}
//second way of display
//stackUsingArray c;
//char ch;
//for (int i = top; i >= 0; i--)
// c.push(this->pop());
//for (int i = c.peekTop(); i >= 0; i--)
//{
// ch=c.pop();
// this->push(ch);
// cout << ch;
//}
}
int search(char ch)
{
for (int i = top; i >= 0; i--)
{
if (a.getAddress()[i] == ch)
return i;
}
return -1;
}
char topDisplay()
{
return a.getAddress()[top];
}
};
class stackUsingLinkedList {};
//functions
string infixToPostfix(string infix);
short prec(char ch);
int main()
{
//infix and postfix
stackUsingArray c;
cout<<infixToPostfix("x+y-z");
system("pause");
return 0;
}
string infixToPostfix(string infix)
{
string postfix = "";
stackUsingArray sta;
char ch;
char test;
for (int i = 0; i < infix.length(); i++)
{
switch (prec(infix[i]))
{
case 0:
postfix.append(1, infix[i]);
break;
case 1:
sta.push(infix[i]);
break;
//case 2:
// ch = sta.pop();
// while (ch != '(')
// {
// postfix.append(1, ch);
// ch = sta.pop();
// }
// break;
case 3:
// if (sta.is_empty())
// {
// goto k270;
// }
// ch = sta.pop();
// while (prec(ch) > 3)
// {
// postfix.append(1, ch);
// if (sta.is_empty()) {
// //sta.push(infix[i]);
// goto k270;
// }
// ch = sta.pop();
// }
// sta.push(ch);
//k270:
// sta.push(infix[i]);
test = sta.topDisplay();
if (sta.is_empty())
{
sta.push(infix[i]);
test = sta.topDisplay();
}
else
{
ch = sta.pop();
test = sta.topDisplay();
if (prec(ch) >= 3)
{
postfix += ch;
}
sta.push(infix[i]);
}
}
}
while (!sta.is_empty())
{
postfix.append(1, sta.pop());
}
return postfix;
}
short prec(char ch)
{
if (ch == '(')
return 1;
if (ch == ')')
return 2;
if (ch == '+')
return 3;
if (ch == '-')
return 3;
if (ch == '*')
return 4;
if (ch == '/')
return 4;
return 0;
}
thanks to #IgorTandetnik I figured out that I should del last item from the array when I pop from stack
I am required to implement a dynamic array that adjusts, dynamically, in accordance with the number of value (temperatures) that are input into the code. I have written the majority of the code for this to be possible, however I have run into a bug and for the life of me, have been unable to locate the issue.
The program is supposed to output the values of temp_a, make temp_b = temp_a, output the value of temp_b, and then clear the value of temp_a, and finally output the values of temp_b once more.
However, when I compile the program, it outputs that the list is full and cannot add any more values, meaning there is a logic error somewhere in the code.
Please forgive me for the lengthy code, as soon as I can locate the error, the code shall be separated into multiple compilations.
#include <iostream>
using namespace std;
class TemperatureList {
private:
int* temp; // pointer to dynamic array
short current_size; // current number of elements
short max_size; // max number of elements allowed in this list
public:
// Overloading assignment operator
void operator =(const TemperatureList& another_list);
// === Constructors ===
// Default constructor
TemperatureList();
// Constructor that accepts an integer parameter that specifies the max length of the list
TemperatureList(int max);
// Copy constructor that accepts another List as parameter
TemperatureList(const TemperatureList& another_list);
// Destructor
~TemperatureList();
// === Modifier functions ===
// add new_value to end of list if there is still space
void add_temperature(int new_value);
// === Accessor functions ===
// return current current_size of the list
short get_current_size();
// === Other functions ===
// return the last element, or 0 if the list is empty, with a warning output
int get_last();
// return element at the position-th position, or 0 if the list is empty, with a warning output
int get_temp(short position);
// returns if current_size == 0
bool set_temp(short position, int value);
// returns if current_size == 0
bool empty();
// returns if current_size == max_size
bool full();
// Output list separated by commas
friend ostream& operator <<(ostream& outs, const TemperatureList& list);
};
int main() {
TemperatureList temp_a;
temp_a.add_temperature(23.5);
temp_a.add_temperature(24.6);
cout << temp_a;
TemperatureList temp_b = temp_a;
cout << temp_b;
temp_a = TemperatureList();
cout << "Now there's no temperatures in a.\n";
cout << temp_a;
cout << "How about temperatures in b?\n";
cout << temp_b;
return 0;
}
void TemperatureList::operator =(const TemperatureList& another_list) {
delete[] temp;
current_size = another_list.current_size;
max_size = another_list.max_size;
if (current_size > 0) {
temp = new int[max_size];
for (int i = 0; i < max_size; i++) {
temp[i] = another_list.temp[i];
}
}
else {
temp = NULL;
}
}
TemperatureList::TemperatureList() {
current_size = 0;
max_size = 0;
temp = NULL;
}
TemperatureList::TemperatureList(int max) : max_size(max) {
current_size = 0;
temp = new int[max];
}
TemperatureList::TemperatureList(const TemperatureList& another_list) {
current_size = another_list.current_size;
max_size = another_list.max_size;
if (current_size > 0) {
temp = new int[max_size];
for (int i = 0; i < max_size; i++) {
temp[i] = another_list.temp[i];
}
}
else {
temp = NULL;
}
}
TemperatureList::~TemperatureList() {
//cout << "== I am in destructor ==\n";
delete[] temp;
}
void TemperatureList::add_temperature(int new_value) {
if (current_size < max_size) {
temp[current_size] = new_value;
current_size++;
}
else {
cout << "Cannot add value to the list. It is full.\n";
}
}
int TemperatureList::get_last() {
if (empty()) {
cout << "The list is empty\n";
return 0;
}
else {
return temp[current_size - 1];
}
}
int TemperatureList::get_temp(short position) {
if (current_size >= position) {
return temp[position - 1];
}
else {
cout << "There is no temperature\n";
return 0;
}
}
bool TemperatureList::set_temp(short position, int value) {
if (current_size >= position) {
temp[position - 1] = value;
return true;
}
else {
return false;
}
}
short TemperatureList::get_current_size() {
return current_size;
}
bool TemperatureList::empty() {
return (current_size == 0);
}
bool TemperatureList::full() {
return (current_size == max_size);
}
ostream& operator <<(ostream& outs, const TemperatureList& list) {
int i;
for (i = 0; i < (list.current_size - 1); i++) {
outs << list.temp[i] << ",";
}
outs << list.temp[i];
return outs;
}
The logic error seems to stem from the fact that you initialize your current_size and max_size to zero. So, unless your run the overloaded constructor (wherein you’re set the max_size), every call to addTemperature() is going to fail the (current_size < max_size) check because they are both equal to zero.
My program keeps getting me bad alloc error when I use a normal function that contains a member function.
The program is about taking some specific inputs from the command line and printing the elements of an array of pointers. This has to be done with array of pointers.
To begin with, I created a class that needs to have 2 strings. One for the name and one for the room. Then I created another class with a size and a pointer to my first class in order to create an array.
My main is at the end, and above main are the 2 normal functions. What is wrong with this code? When I type the commands for the first time of the loop it works until I enter a command that connects to a normal function. Probably something is wrong there but I can't seem to find it.
#include <iostream>
#include <string>
using namespace std;
class Address
{
private:
string name;
string room;
public:
Address(){};
Address(string, string);
string get_name();
string get_room();
void change_room(string);
};
Address::Address (string n, string r)
{
name = n;
room = r;
}
string Address::get_name()
{
return name;
}
string Address::get_room()
{
return room;
}
void Address::change_room(string change)
{
room = change;
}
//end of Address class
class Address_Book
{
private:
int size;
Address* addresses;
public:
Address_Book();
~Address_Book(){ delete[] addresses;}
void add(Address);
void move(string, string);
int get_size();
Address location(int);
int find(string);
void clear();
void remove_address(string);
int exists(string);
void sort();
};
Address_Book::Address_Book()
{
int s = 0;
size = s;
addresses = new Address[s];
}
void Address_Book::add(Address add)
{
Address* temp = new Address [size + 1];
for (int i = 0; i < size; i++)
{
temp[i] = addresses[i];
}
temp[size] = add;
delete[] addresses;
addresses = temp;
size ++;
}
void Address_Book::move(string name, string newroom)
{
for (int i = 0; i < size ; i++)
{
if (addresses[i].get_name() == name )
{
addresses[i].change_room(newroom);
}
}
}
void Address_Book::remove_address(string name)
{
Address* temp = new Address [size - 1];
for (int i = 0; i < size; i++)
{
if (addresses[i].get_name() != name)
{
temp[i] = addresses[i];
}
else if (addresses[i].get_name() == name)
{
for (int j = i + 1; j < size; j++)
{
temp[i] = addresses[j];
i++;
}
break;
}
}
delete[] addresses;
addresses = temp;
size--;
}
int Address_Book::get_size()
{
return size;
}
Address Address_Book::location(int index)
{
return addresses[index];
}
void Address_Book::sort()
{
Address temp;
for (int i = 0; i < size; i++)
{
for(int j = 0; j < size - 1; j++)
{
if (addresses[j].get_room() > addresses[j + 1].get_room())
{
temp = addresses[j];
addresses[j] = addresses[j + 1];
addresses[j + 1] = temp;
}
}
}
for (int i = 0; i < size; i++)
{
if (addresses[i].get_room() == addresses[i + 1].get_room())
{
if (addresses[i].get_name() > addresses[i + 1].get_name())
{
temp = addresses[i];
addresses[i] = addresses[i + 1];
addresses[i + 1] = temp;
}
}
}
}
void Address_Book::clear()
{
Address * temp = new Address[0];
delete[] addresses;
addresses = temp;
size = 0;
}
int Address_Book::find(string name)
{
for (int i = 0; i < size; i++)
{
if (addresses[i].get_name() == name)
{
return i;
}
}
return -1;
}
//end of Address_Book class
void find(string name, Address_Book addbook)
{
int index = addbook.find(name);
cout << index << endl;
if (index > -1)
{
cout << addbook.location(index).get_name() << " is in room " <<
addbook.location(index).get_room() << endl;
}
else
{
throw runtime_error("entry does not exist.");
}
}
void remove_add(string name, Address_Book book)
{
int exist = book.find(name);
if (exist > -1)
{
book.remove_address(name);
}
else
{
throw runtime_error("entry does not existt.");
}
}
int main()
{
Address_Book addbook;
string action, in_name, in_room;
do
{
try
{
cout << "> ";
cin >> action;
if (action == "add")
{
cin >> in_name >> in_room;
Address newadd(in_name, in_room);
addbook.add(newadd);
}
else if (action == "move")
{
cin >> in_name >> in_room;
addbook.move(in_name, in_room);
}
else if (action == "remove")
{
cin >> in_name;
remove_add(in_name, addbook);
}
else if (action == "find")
{
cin >> in_name;
find(in_name, addbook);
}
else if (action == "list")
{
addbook.sort();
for (int i = 0; i < addbook.get_size(); i++)
{
cout << addbook.location(i).get_name() << " is in room
" << addbook.location(i).get_room() << endl;
}
}
else if (action == "clear")
{
addbook.clear();
}
else
{
throw runtime_error("input mismatch.");
}
}
catch (runtime_error& e)
{
cerr << "error: " << e.what() << endl;
}
}while (action != "exit");
return 0;
}
The function remove_add needs to get the address book object by reference or by pointer.
The way it is now, it removes from a copy of the address book.
It should look like this:
void remove_add(string name, Address_Book& book)
{
int exist = book.find(name);
if (exist > -1)
{
book.remove_address(name);
}
else
{
throw runtime_error("entry does not existt.");
}
}
Also, you should probably do something different in case size == 1 in the following function. e.g. set addresses to NULL, zero or nullptr if your compiler supports it.
void Address_Book::remove_address(string name)
{
Address* temp = new Address[size - 1];
for (int i = 0; i < size; i++)
{
if (addresses[i].get_name() != name)
{
temp[i] = addresses[i];
}
else if (addresses[i].get_name() == name)
{
for (int j = i + 1; j < size; j++)
{
temp[i] = addresses[j];
i++;
}
break;
}
}
delete[] addresses;
addresses = temp;
size--;
}
Have fun learning the language and good luck :)
The exact commands that lead to your problem are not specified in your question, so I poked around a little bit until the code crashed with a segmentation fault.
Valgrind and Dr. Memory are awesome tools for finding root causes of such problems. In your case:
$ g++ -g 46865300.cpp
$ valgrind ./a.out
> add foo bar
> list
==102== Invalid read of size 8
==102== at 0x4EF4EF8: std::basic_string<char, std::char_traits<char>, std::allocator<char> >::basic_string(std::string const&) (in /usr/lib64/libstdc++.so.6.0.19)
==102== by 0x401354: Address::get_room() (46865300.cpp:33)
==102== by 0x401C05: Address_Book::sort() (46865300.cpp:152)
==102== by 0x4026A3: main (46865300.cpp:262)
==102== Address 0x5a17410 is 8 bytes after a block of size 24 alloc'd
==102== at 0x4C2A8A8: operator new[](unsigned long) (vg_replace_malloc.c:423)
==102== by 0x4014BF: Address_Book::add(Address) (46865300.cpp:74)
==102== by 0x40245C: main (46865300.cpp:243)
It says that the following code performs out-of-bounds access:
150 for (int i = 0; i < size; i++)
151 {
152 if (addresses[i].get_room() == addresses[i + 1].get_room())
153 {
154 if (addresses[i].get_name() > addresses[i + 1].get_name())
I guess the loop condition should use "size - 1" instead of "size".
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.
I am trying to implement a system that would perform something like say the user enters 4 5 +. It would add the 4 and 5 (9) and push 9 into the stack.
For some reason the values in the stack are huge numbers so I believe it has something to do with a pointer or accessing a wrong field but I'm pulling my hair out trying to find the error. Any help on what I'm doing wrong?
#include "stack.h"
int main()
{
stack Test;
bool stop = false;
float runningtotal = 0;
while (stop == false)
{
char input;
cin >> input;
if (input == '+') {
int value1 = Test.top();
Test.pop();
int value2 = Test.top();
Test.pop();
cout << value1+value2 << endl;
Test.push(value1 + value2);
}
cout << Test.top();
std::getchar();
std::getchar();
}
And the implementation of stack
#include "stack.h"
stack::stack()
{
maxsize = MaxSize;
currentsize = 0;
sptr = new StackElement[maxsize];
}
stack::~stack()
{
delete [] sptr;
}
void stack::push(StackElement data)
{
if (currentsize < maxsize)
{
sptr[currentsize] = data;
currentsize++;
} else {
cout << "Stack is full ;-;";
}
}
void stack::pop()
{
if (currentsize == 0) {
cout << "Empty stack? ;-;";
return;
}
currentsize--;
}
StackElement stack::top()
{
if (currentsize == 0) {
cout << "Empty stack u ninja ;-;";
return NULL;
} else {
return (sptr[currentsize]);
}
}
void stack::push(StackElement data)
{
if (currentsize < maxsize)
{
sptr[currentsize] = data;
currentsize++; //<--- incrementing after so nothing in [currentsize] now
} else {
cout << "Stack is full ;-;";
}
}
StackElement stack::top()
{
if (currentsize == 0) {
cout << "Empty stack u ninja ;-;";
return NULL;
} else {
return (sptr[currentsize]);// should use currentsize-1
// latest filled cell
// since its pushing from top
}
}
Be sure to convert those ascii codes(49 ish) from keyboard to integer type explanations.
input - 48 should do it.