Loop issue concerning doubles

When I run my program I enter the amount of sales I need, then enter those sales. Then the main function should print the info that was returned. But it prints way too many sales then I entered. I think the problem is in the for loop where I state i<*p. But I don't know how else to limit the loop since I'm not returning the numSales. Thanks for any help :)

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
  /* Write a function called getSalesList.  It should ask the user how
   many sales will be entered.  It should dynamically create an array
   of doubles for that number of sales.  It should prompt the user to enter
   a sales amount which is stored in the array until all sales are entered.
   A pointer to this array should be returned from the function.

   Write a main method that calls this function and prints the information
   that was returned, then deletes the array. */

#include <iostream>

using namespace std;

double* getSalesList (int);

int main ()
{
	int numSales = 0;	

	double* p = getSalesList(numSales);

	for (int i=0; i<*p; i++) //here is where I think the problem is
		cout << i+1 << " $" << p[i] << endl;

	delete [] p;

	return 0;
}

double* getSalesList (int numSales)
{	
	cout << "How many sales will be entered?: ";
	cin >> numSales;
	
	double *p = new double [numSales];

	for (int i=0; i<numSales; i++)
		*(p+i) = i;

	for (int i=0; i<numSales; i++)
	{
		cout << "Enter the sales amount for slot " << i+1 << ": $";
		cin >> p[i];
	}

		return p;
}
Why are you using *p as the limit variable in your for loop?
If you want to print each of the sales, then your limit variable should be numSales.
for (int i=0; i<numSales; i++)

Well I want to do that, but I'm not returning numSales. So when I do that the program lets me enter the sales, but it returns nothing b/c numSales = 0.

Although I just fixed it, I changed the parameters on the function to int &numSales. (I'm an idiot)
Last edited on
Topic archived. No new replies allowed.