Click here to Skip to main content
15,896,730 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
See more:
Okay guys So I have an exercise to do for a book store program in c++ primer. It is a book but I can't do this exercise :/


Write a program that reads several transactions for the same
ISBN. Write the sum of all the transactions that were read. (This is what I have to do)

I made a code that will add two together but How can I modify it to allow unlimited inputs.

C++
#include <iostream>
#include "Sales_item.h"
int main()
{
Sales_item item1, item2;
std::cin >> item1 >> item2; // read a pair of transactions
std::cout << item1 + item2 << std::endl; // print their sum
return 0;
}


I would like to to read multiple inputs and allow me to end statement to print result. It's a noob question I know. Any help would be appreciated :)
Posted
Comments
Sergey Alexandrovich Kryukov 27-Jan-14 14:09pm    
How come you call the pair of objects read from input a "transaction"?
—SA

Loop! ...create a loop that reads input data and store it off to an array. If you don't want to do the array size management yourself, use a container of some sort such as a std::vector (containers are just helpers that "contain" the actual data array internally).
 
Share this answer
 
You could use a linked list, of indeterminate size or consider http://www.cplusplus.com/reference/vector/vector/vector/ Then all you need to do is loop until end command entered, add values to your vector, after your end command entered, get an iterator to the vector create a simple variable to store the sum, sum everything in your vector while you iterate over the loop.


The concept is the same for a linked list, however one allows you to use the stl (vector) the other approach using a linked list doesn't have to.
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900