0

Hello if I input some numbers into this:

int main() {
    int currval = 0, val = 0;
    if (std::cin >> currval) {
        int cnt = 1;
        while (std::cin >> val) {
            if (val == currval) {
                ++cnt;
            }
            else {
                std::cout << currval << " occurs " << cnt << " times. " << std::endl;
                currval = val;
                cnt = 1;
            }
        }
        std::cout << currval << " occurs " << cnt << " times. ";
    }

    return 0;
}

it wont output how many times the last value appears. I tried running through the code on paper and I found that it should print how many times the last number occurs. Its weird because if I enter some more numbers after it finds how many time each of the first group of numbers appear, it will print how many time the last value of the first group appears in the second print thing. you can compile and run it and see if you get different results. I am new to c++ so anything will help. Thanks.

Vityou
  • 152
  • 1
  • 11

1 Answers1

2

If you need a stream to be flushed at a particular place, you need to flush it. Otherwise, it can be internally buffered and flushed later.

David Schwartz
  • 179,497
  • 17
  • 214
  • 278
  • 3
    And as somebody who is not new to c++ knows, printing an `endl` causes a flush. – enhzflep Feb 04 '15 at 23:32
  • By default, attempting to read `std::cin` will cause `std::cout` to be flushed. [See here](http://stackoverflow.com/questions/14052627/why-do-we-need-to-tie-cin-and-cout). (So, only the final `cout` needs to be explicitly flushed) – M.M Feb 05 '15 at 00:05
  • So your saying if I don't "flush" it (fancy word no comprendo) with `std::endl` it might work. Can you explain what flushing and buffering mean. – Vityou Feb 05 '15 at 03:56
  • Sorry if I sound ignorant I am used to python. – Vityou Feb 05 '15 at 03:57