How to store number of times a variable is accessed.

I'm trying to make this program output the number of times an item has been typed in the program but I can't figure out how to do this as I am a C++ Nube. Any help is greatly appreciated.







#include <iostream>


using namespace std;
int main ()
{
int Number;
int item;
item = 2;
string arrayOfIntegers [item] ;
while (Number != 0)
{
cout << "Please enter a 7-digit code or enter 0 to stop the program. ";
cin >>Number;


arrayOfIntegers[0] = "Chiquita Brand Bananas";
arrayOfIntegers[1] = "Gala Brand Apples";
arrayOfIntegers[1] = "Joshs Stove Top Popcorn with 2 cups of butter";



if (Number == 3453456)

{
int Count = 0;
cout << arrayOfIntegers[0] << endl;
Count++;
cout << "Number of items: "<< Count << endl;
}
else if (Number == 3453457)
{
cout << arrayOfIntegers[1] << endl;
}
else if (Number == 3453458)
{
cout << arrayOfIntegers[2] << endl;
}
}
cout << "Thanks for using Fridge Master 7000" << endl;





return 0;
}
As you can see I've been trying to use:

int Count=0;
Count++;

But it doesn't seem to record properly. I'd like a separate count for each item in the program.

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

class InputHelper {
	char const* prompt_ ;
	std::ostream& os_ ;
	std::istream& is_;
	int& n_ ;
public:

	InputHelper(std::ostream& o, char const* prompt, std::istream & i, int& n) 
		: prompt_(prompt), os_(o), is_(i), n_(n) {}

	std::istream & operator()()
	{
		os_ << prompt_ ;
		is_ >> n_ ;
		return is_ ;
	}
};

void print(std::ostream & os, const std::map<int,unsigned> m)
{
	std::map<int, unsigned>::const_iterator m_iter = m.begin() ;
	while ( m_iter != m.end() )
	{
		os << (*m_iter).first << " occurred " << (*m_iter).second << " times.\n" ;
		++m_iter ;
	}
}

int main ()
{

	std::map<int, unsigned> item_map ;

	int num ;
	InputHelper get_input(std::cout, "Please enter a number (0 to quit):  ", std::cin,  num) ;
	
	while (get_input() && num != 0)
		item_map[num]++ ;

	print( std::cout, item_map ) ;
} 
Last edited on
My compiler (Eclipse) won't run #include <map>
Is there a way to combat this?
update it, or if that doesn't work, use another IDE, <map> is a standard c++ library, any decent IDE/compiler should know what it is.

that large piece of code is way too complex for a newbie anyway, I suggest you ignore it and try something easier and manual.

I can't understand what your code is meant to do, although you assign [1] twice, e.g:

1
2
arrayOfIntegers[1] = "Gala Brand Apples";
arrayOfIntegers[1] = "Joshs Stove Top Popcorn with 2 cups of butter";


why do you want to know how many times it has been accessed anyway?
Topic archived. No new replies allowed.