C++ looping?

I'm not sure if this has to do with looping, but I need help because I know how to total up the amount purchased but I don't know how to keep it so there is no limit to the items that can be purchased. help please?

A function that asks the user for purchased item prices and calculates the total purchase amount. There should no limit on how many items that can be purchased.
Hmm If I understand right, you want something like this:

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

using namespace std;

vector<double> vPriceList;

double getTotalCost() {

 double dRet = 0.0;

 for (int i = 0; i < (int)vPriceList.size(); ++i) 
  dRet += vPriceList[i];

 return dRet;

}

int main() {

 vPriceList.push_back(3.25);
 vPriceList.push_back(5.00);

 cout << "Total Cost: " << getTotalCost() << endl;

}


A Vector a Standard Template Library (STL) container that is used as a dynamic array. It's much easier and safer to use then instead of creating your own dynamic arrays. Dynamic arrays still have their own purpose thou :)
If you need not to keep the individual prices rather interested in the sum total then U can use the below program for the same...

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
#include<stdio.h>
#include <memory.h>
#include <string.h>

int main()
{
	int more = 1;

	double price = 0.0;
	double totPrice = 0.0;

	while(more)
	{
		printf("Purchased item price : ");
		scanf("%lf",&price);
		totPrice += price;
		
		char userInput[5];
		memset(userInput,0,sizeof(userInput));
		fflush(stdin);
		printf("---More(y/n)---");
		gets(userInput);

		if(stricmp(userInput,"y")==0 || strcmp(userInput,"")==0)
			more = 1;
		else
			more = 0;
	}

	printf("Total amount spent on purchase : %lf ",totPrice);
	return 0;
}


But if U have to keep the individual values then U have use the Dynamic Array.
Topic archived. No new replies allowed.