Top is not returning empty string when count is 0; Second Code is Main (dont cha
ID: 3752678 • Letter: T
Question
Top is not returning empty string when count is 0; Second Code is Main (dont change), first is my functions
#include <iostream>
#include <string>
#include "..........Desktopderys workall 2018 workstack.h"
using namespace std;
Stack::Stack()
{
count = 0;
}
int Stack::size() {
if (count == -1) {
return count++;
}
else {
return count;
}
}
void Stack::push(string item) {
data[count] = item;
count++;
}
void Stack::pop() {
string temp;
if (count == 0) {
count++;
}
else {
count--;
}
}
string Stack::top() {
if (count == 0) {
return "";
}
else
return data[count - 1];
}
int main() {
Stack s;
test(s.size() == 0, "Should initially be empty");
s.push("Eric");
s.push("Mary");
s.push("Joseph");
test(s.size() == 3, "Should have 3 items");
s.pop();
test(s.size() == 2, "Should have 2 items");
s.push("Pimple");
test(s.size() == 3, "Should have 3 items");
test(s.top() == "Pimple", "Top should be Pimple");
s.pop();
test(s.top() == "Mary", "Pimple should have been popped. lol");
s.pop();
test(s.top() == "Eric", "Mary should have been popped.");
s.pop();
test(s.size() == 0, "Should have 0 items");
s.pop();
test(s.size() != -1, "Should have 0 items not -1 items!");
test(s.top() == "", "top() should return empty string when count < 0");
cout << "Assignment complete." << endl;
system("pause");
return 0;
}
Explanation / Answer
#include <iostream>
#include <string>
#include "..........Desktopderys workall 2018 workstack.h"
using namespace std;
Stack::Stack()
{
count = 0;
}
int Stack::size() {
// if no of elements is negative or 0
if (count <= 0) {
// set the no of elements to 0
count = 0;
return count;
}
else {
return count;
}
}
void Stack::push(string item) {
data[count] = item;
count++;
}
void Stack::pop() {
// string temp;
//if (count == 0) {
// count++;
//}
//else {
// if the stack is not empty
if( count > 0 )
// reduce the number of elements in stack
count--;
}
}
string Stack::top()
{
// if the stack is empty
if (count <= 0) {
// set the no of elements to 0
count = 0;
return "";
}
// if the stack is not empty
else
return data[count - 1];
}
int main() {
Stack s;
test(s.size() == 0, "Should initially be empty");
s.push("Eric");
s.push("Mary");
s.push("Joseph");
test(s.size() == 3, "Should have 3 items");
s.pop();
test(s.size() == 2, "Should have 2 items");
s.push("Pimple");
test(s.size() == 3, "Should have 3 items");
test(s.top() == "Pimple", "Top should be Pimple");
s.pop();
test(s.top() == "Mary", "Pimple should have been popped. lol");
s.pop();
test(s.top() == "Eric", "Mary should have been popped.");
s.pop();
test(s.size() == 0, "Should have 0 items");
s.pop();
test(s.size() != -1, "Should have 0 items not -1 items!");
test(s.top() == "", "top() should return empty string when count < 0");
cout << "Assignment complete." << endl;
system("pause");
return 0;
}