I know this is a horrible way to do this, but I'm trying to test out several things that I've learned at once in this code. It's meant to ask you how many numbers you want to add using dynamic memory, then push them on to the stack, and add them to the register of "answer." It's not working for some reason, and I was wondering if someone could help. What I'm really trying to learn is how to incorporate stacks in functions. Thanks!

#include<iostream>
#include<new>
#include<cmath>
#include<cstdlib>
#include<string>
#include<stack>

using namespace std;

int nPush(int b, stack<int> a)
{
	a.push(b);
	return 0;
}

int nPop(stack<int> d, int *p1)
{
	*p1 += d.top();
	d.pop();
	return 0;
}

int main()
{

	int i, n, k, j;
	int answer = 0;
	int *dm;
	stack<int> nNumbers;

	cout << "Enter the number of numbers you'd like to add: ";
	cin >> n;
	cout << endl;
	dm = new (nothrow) int[n];

	for(i=0; i<n; i++)
	{
		cout << "Enter number: ";
		cin >> dm[i];
		cout << endl;
		nPush(dm[i],nNumbers);
	}

	cout << "Stack size: " << nNumbers.size() << endl;

	for(j=1; j<n+1; j++)
	{
		nPop(nNumbers, &answer);
		cout << k+1 << ": " << answer << endl;
		k++;
	}

	cout << "The answer is: " << answer << endl;
	delete[] dm;

	system("PAUSE");
	return 0;

}

The stack parameter to those two functions have to be passed by reference, not by value int nPush(int b, stack<int>& a) Also you have to initialize the value of k before using it on line 49.

The stack parameter to those two functions have to be passed by reference, not by value int nPush(int b, stack<int>& a) Also you have to initialize the value of k before using it on line 49.

I kind of love you now...

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.