Problems with Stacks.
May 20, 2018 at 10:24pm UTC
The program I've written manages to print out a few, then spits out the Stack Empty error. I suppose I just need a second pair of eyes to tell me where I messed up.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
struct info
{
string name;
double avg;
};
class stack {
private :
int array[50];
int top;
public :
stack() {
top = 0;
}
bool isempty() {
if (top == 0)
return true ;
else
return false ;
}
bool isfull() {
if (top == 50)
return true ;
else
return false ;
}
void push(int n) {
if (!isfull()) {
array[top] = n;
top++;
}
else {
cout << "Stack is Full" << endl;
}
}
int pop() {
if (!isempty()) {
top = top - 1;
return array[top];
}
else {
cout << "Stack empty" << endl;
return -1;
}
}
};
class PlayerInfo
{
private :
info list[100];
stack st_high;
stack st_low;
int count;
public :
PlayerInfo() { count = 0; }
void AddPlayer(string name, double batAvg)
{
list[count].name = name;
list[count].avg = batAvg;
count++;
}
void printHigh()
{
double max;
max = list[0].avg;
for (int i = 0; i < count; i++) {
if (list[i].avg > max)
max = list[i].avg;
}
for (int i = 0; i < count; i++) {
if (list[i].avg == max)
st_high.push(i);
}
while (!st_high.isempty()) {
cout << list[st_high.pop()].name << " " << list[st_high.pop()].avg << endl;
}
}
void printLow() {
double min;
min = list[0].avg;
for (int i = 0; i<count; i++) {
if (list[i].avg < min)
min = list[i].avg;
}
for (int i = 0; i<count; i++) {
if (list[i].avg == min)
st_low.push(i);
}
while (!st_low.isempty()) {
cout << list[st_low.pop()].name << " " << list[st_low.pop()].avg << endl;
}
}
};
int main()
{
PlayerInfo pl;
ifstream infile;
string name;
double avg;
infile.open("avgs.txt" ); // Assuming the name of input file is "Input.txt"
while (infile >> name >> avg)
{
pl.AddPlayer(name, avg);
}
pl.printHigh();
pl.printLow();
infile.close();
return 0;
}
Here's a link to avgs.txt:
http://programming.msjc.edu/cppii/avgs.txt
Last edited on May 20, 2018 at 10:52pm UTC
May 20, 2018 at 10:38pm UTC
Look more closely at this in the printHigh function:
1 2 3
while (!st_high.isempty()) {
cout << list[st_high.pop()].name << " " << list[st_high.pop()].avg << endl;
}
You're popping twice from the stack. You need to call pop only once, save the value and use it twice.
1 2 3 4
while (!st_high.isempty()) {
int i = st_high.pop();
cout << list[i].name << " " << list[i].avg << endl;
}
Same problem in the printLow function.
Last edited on May 20, 2018 at 10:39pm UTC
May 20, 2018 at 10:58pm UTC
Thank you very much!
Topic archived. No new replies allowed.