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