Question: Would you be able to figure out how to fix the C++ code to work? Copying section is not working. header file: #include #include using
Would you be able to figure out how to fix the C++ code to work? Copying section is not working.
header file:
#include
using namespace std;
class Stack { private: string* stack; int count; int size; public: Stack(int size) { stack = new string[size]; count = 0; this->size = size; } ~Stack() { delete[] stack; //deletes entire stack } void push(string item) {
if (count == size) { throw overflow_error("Stack is full!"); } stack[count] = item; count++; } string top() { if (count == 0) { throw underflow_error("Stack is empty!"); } return stack[count - 1]; } string pop() { if (count == 0) { throw underflow_error("Stack is empty!"); } count = count - 1; return stack[count]; } bool empty() { return (count == 0); } int get_Count() { return count; } int get_Size() { return size; } };
Main file:
#include
using namespace std;
void copy_stack(Stack A, Stack& B) { int size2 = A.get_Size(); Stack C(size2); while (!A.empty()) { C.push(A.top()); A.pop(); } while (!C.empty()) { B.push(C.top()); C.pop(); }
}
int main() {
static int capacity, capacity2; string repeat, input, input2; cout << "How many elements can do you want in the 1st stack? " << endl; cin >> capacity; Stack myStack(capacity); for (int i = 1; i <= capacity; i++) { cout << "Please enter stack["<> input; myStack.push(input); } cout << "How many elements can do you want in the 2nd stack? " << endl; cin >> capacity2; Stack myStack2(capacity2); for (int i = 1; i <= capacity2; i++) { cout << "Please enter stack[" << i << "]" << endl; cin >> input2; myStack2.push(input2); }
copy_stack(myStack, myStack2);
cout << "1st Stack: " << endl; while (!myStack.empty()) { cout << myStack.top() << endl; myStack.pop(); } cout << "Copied 2nd Stack: " << endl; while (!myStack.empty()) { cout << myStack.top() << endl; myStack.pop(); } //myStack.pop(); return 0; }
This program crashes once it goes to the copy function, which leads to an exception for overflow error. I'm not sure which part I am doing incorrectly.
Step by Step Solution
There are 3 Steps involved in it
Get step-by-step solutions from verified subject matter experts
