I started with book c++ primer 5th edition. In first chapter there is a prog in which i should type smtn like 21 12 32 12 and it should say:
21 occures 1 time
12 occures 2 times
32 occures 1 time
but when i start the prog and type the numbers i get
21 occures 1 time
12 occures 1 times
32 occures 1 time
and thats for every combination.
Here is the code that they wrote. Am I doing smtn wrong are are they? Pls help :P
#include <iostream>
int main()
{
// currVal is the number we're counting; we'll read new values into val
int currVal = 0, val = 0;
// read first number and ensure that we have data to process
if (std::cin >> currVal) {
int cnt = 1; // store the count for the current value we're processing
while (std::cin >> val) { // read the remaining numbers
if (val == currVal) // if the values are the same
++cnt; // add 1 to cnt
else { // otherwise, print the count for the previous value
std::cout << currVal << " occurs " << cnt << " times" << std::endl;
currVal = val; // remember the new value
cnt = 1; // reset the counter
}
} // while loop ends here
// remember to print the count for the last value in the file
std::cout << currVal << " occurs " << cnt << " times" << std::endl;
} // outermost if statement ends here
return 0;
}
You could store all the numbers into a list and then process them afterwards?
My favorite simple technique for counting occurrences is using the std::map container
1 2 3 4 5 6 7 8 9 10 11 12 13 14
#include <map>
#include <iostream>
int main() {
std::map<int, int> freqs;
int num;
while(std::cin >> num) {
freqs[num]++; //this works because int values start at 0 inside of maps
}
for(auto it = freqs.begin(); it != freqs.end(); it++) {
std::cout << it->first << " occurred " << it->second << " times." << std::endl;
}
return 0;
}
The program counts how many items in a sequence which is then changed with a different number.
example:
21 21 21 21 77 99 99 21 21 21 66 66
21 occurs 4 times in sequence!!
77 occurs 1 time
99 occurs 2 time
21 occurs 3 time
66 occurs 2 times
Blocks of code are easier to see if you indent them.
#include <iostream>
int main()
{
// currVal is the number we're counting; we'll read new values into val
int currVal = 0, val = 0;
// read first number and ensure that we have data to process
if (std::cin >> currVal)
{
int cnt = 1; // store the count for the current value we're processing
while (std::cin >> val) // read the remaining numbers
{
if (val == currVal) // if the values are the same
++cnt; // add 1 to cnt
else { // otherwise, print the count for the previous value
std::cout << currVal << " occurs " << cnt << " times" << std::endl;
currVal = val; // remember the new value
cnt = 1; // reset the counter
}
} // while loop ends here
// remember to print the count for the last value in the file
std::cout << currVal << " occurs " << cnt << " times" << std::endl;
} // outermost if statement ends here
return 0;
}