stack

The problem is on like 14 and 16 where the compiler tells me that push and pop are not declerd in the scope.

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
#include<iostream>

using namespace std;

struct elem{
        int key;
        elem *next;
       }*start=NULL;
int main()
{int n;
cout<<"Vuvedete chislo";

while(cin>>n)
{ push(n);}
cout<<"Stek";
while(  pop(n))
{cout<<n<<"";}
}


void push(int n)//добавя нов елемент в стека
{elem *p=start;
start=new elem;//създаване на нов елемнт
start->key=n;
start->next=p;//установява нов връх
}

int pop (int &n)
{if(start)
  {
   n=start->key;
   elem *p=start;
   start=start->next;
   delete p;
   return 1;
   }else return 0;//стека е празен
}

Before main...

1
2
void push( int n );
int pop( int &n );
The compiler says they're undefined because is has to see the functions before you want to use them. So when it gets to line 14, it has no idea of what push() could be. So, you have two choices.
You can 1) move the entire function definitions so that they are before main (not recommended), or 2) place function prototypes before main, letting the compiler know "this is a function; I'll define it later".

The prototype method is what I suggest because it generally looks cleaner, and is easy to understand. Plus, when showing someone complex code, it's a good "road map" of functions (so they don't have to search your code every time they want to know what is returned by pop, for example).
I have another question.What do I have to if I want to make a function that removes all the negative numbers
Using a stack, you don't selectively remove data. There's only pop() and push() functions because there's only one spot you ever need to read from or write to - and that's the top of the stack. That's the definition of a stack. If you need to get values other than the top, you should use a different data type.

A criticism: I don't think pop() ought to return anything. This is generally done by a top() function. I'd write a top() function, then do this instead of what your original post does at line 16:
1
2
3
4
while (start) { // Implying that start is not null
    cout << top() << endl;
    pop();
}
Is it possible to have a stack where all the numbers are,and use a second stack with a loop to get the numbers I need?
Anything's possibly.
ivo1, great thinking. And ResidentBiscuit is completely right - your program will do whatever you tell it to. For me anyway, that's the joy in programming.
Topic archived. No new replies allowed.