This is supposed to take up to 100 char variables and reverse it, but after the
ID: 3875922 • Letter: T
Question
This is supposed to take up to 100 char variables and reverse it, but after the 9th character, it somehow collapses. Where is the problem coming from?
#include "stack.h"
#include <iostream>
#include <string>
using namespace std;
int main(){
stack arrayStack;
string input;
while(cout << "Enter a String: ", getline(cin, input)){
for(int i = 0; i < input.size(); i++){
arrayStack.push(input[i]);
}
while(!arrayStack.isEmpty()){
cout << arrayStack.pop();
}
cout << endl;
}
return 0;
}
#include<iostream>
#define STACK_CAPACITY 1000
using namespace std;
class stack{
int count;
char stacks [];
void error(const char * msg){
cerr << "Error: " << msg << endl;
}
public:
stack(){
count = 0;
stacks [100];
}
void push(char c){
if(isFull()){
error("Cannot push on to a full stack");
}
stacks[count] = c;
++count;
}
char pop(){
if(isEmpty()){
error("Cannot pop from an empty stack");
}
return stacks[--count];
}
char top(){
if(isEmpty()){
error("peaking on an empty stack");
}
return stacks[count - 1];
}
bool isEmpty(){
return count <= 0;
}
bool isFull(){
return count >= STACK_CAPACITY;
}
~stack(){
}
};
Enter a String: hello world
sow olleh
Enter a String: 1234512345
532154321
Enter a String: 1234567890
:87654321
Enter a String: 12345
54321
Enter a String: 123456
654321
Enter a String: 1234567
7654321
Enter a String: 12345678
87654321
Enter a String: 123456789
:87654321
Explanation / Answer
The problem seems to be in stack class. The following code has issues:
class stack{
int count;
char stacks[]; //??? This is not ok
void error(const char *msg){
cerr << "Error:" << msg << endl;
}
public:
stack(){
count = 0;
stacks[100] //????? This is not ok
}
The correct code should be:
class stack{
int count;
char stacks[STACK_CAPACITY]; // You can specify the size here. Please take care that isFull also gets modified accordingly
void error(const char *msg){
cerr << "Error:" << msg << endl;
}
public:
stack(){
count = 0;
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.