fork download
  1. #include <iostream>
  2.  
  3. int main()
  4. {
  5. // currVal is the number we're counting; we'll read new values into val
  6. int currVal = 0, val = 0;
  7. // read first number and ensure that we have data to process
  8. if (std::cin >> currVal) {
  9. int cnt = 1; // store the count for the current value we're processing
  10. while (std::cin >> val) { // read the remaining numbers
  11. if (val == currVal) // if the values are the same
  12. ++cnt; // add 1 to cnt
  13. else { // otherwise, print the count for the previous value
  14. std::cout << currVal << " occurs "
  15. << cnt << " times" << std::endl;
  16. currVal = val; // remember the new value
  17. cnt = 1; // reset the counter
  18. }
  19. } // while loop ends here
  20. // remember to print the count for the last value in the file
  21. std::cout << currVal << " occurs " << cnt << " times" << std::endl;
  22. } // outermost if statement ends here
  23. return 0;
  24. }
Success #stdin #stdout 0s 3460KB
stdin
1 2 3 4 4
stdout
1 occurs 1 times
2 occurs 1 times
3 occurs 1 times
4 occurs 2 times