A small problem here

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
#include <iostream>
using namespace std;

class Stack {
public:
Stack() { sp = 0; }  
void operator<<(int);
int operator>>(string);
private:
int sp;               
int buffer[20];  
static void Error() { cout << "Stack Error"<<endl; }
};

void Stack::operator<<(int x) 
{
if(sp == 20)        
Error();
else
buffer[sp++] = x; 
}                            

int Stack::operator>>(string s)         
{ 
if (s == "pop")
{
if(sp == 0) 
Error();
else
return buffer[--sp];    
}   
}

int main()
{
Stack A;
A<<5; A<<44; A<<78; A<<456;
cout<<(A>>"pop")<<endl;
cout<<(A>>"pop")<<endl;
cout<<(A>>"pop")<<endl;
cout<<(A>>"pop")<<endl;
cout<<(A>>"pop")<<endl;
system("pause");
}                         


The code works OK except when I want to test the extra pop that leads to the Error message(Line 42), it gives me an additional,unintended line of output of "16384". What is wrong with my program and how to fix it? Thanks.
as an operator that returns an int, >> must return and int. You could use try catch blocks, or make another function to check if the stack is empty. Then you can just simply make a loop that outputs until it is empty.
Last edited on
Topic archived. No new replies allowed.