1

So...here is my code that refer to C++ Primer 1.4.4 section.

#include <iostream>
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." << std::endl;
  }
  return 0;
}

I have to admit that the simple program basically work normally. But for the further discussion, I'd like refer to a asciinema recording in the first place.

In the recording I run ./a.out three times. In the first time, I typed numbers and press enter the first two recording printed and only after ctrl + D was pressed the third (last) result was printed. From previous sections in the book, I know ctrl + D is used to feed some symbols to stop the while loop. But I really wonder if it (ctrl + D here cause a strange stop) works just like as same as authors' expectation for there is no mention on how keys was pressed exactly about that example in the book.

In the last two runs, my first approach is press ctrl + D (the first result printed) and enter (the second result printed), then following several enters (no respond except more lines). Lastly, I pressed ctrl + D (the third result printed).

My last approach is press ctrl + D for two times. The first result printed on the first press and the last two came out on the second press.

With these two runs comes my confusing that after press ctrl + D (I think) there should be a stopping signal in the end of cin stream. So why did the while loop not stop? I'd appreciate a lot if anyone can explain the process behind it.

My working environment is urxvt on Manjaro Linux with zsh and oh-my-zsh installed.

Page David
  • 1,309
  • 2
  • 14
  • 25
  • 2
    You mentioned ctrl + D is supposed to send a stopping signal. However it really means end of file and has no effect if the program isn't reading input from the terminal. – edhu Jul 30 '18 at 09:45
  • @BDH So, does that means program will not remember there is a ctrl + D after ints in my second and last example? But how to explain the loop does not continue after the first result printed in last two cases? – Page David Jul 30 '18 at 11:43
  • 1
    See https://stackoverflow.com/q/49896165/4074081. This looks like the same glibc bug. – dewaffled Jul 30 '18 at 14:56
  • @dewaffled Thanks your helpful link. So here is my understanding: in the first case that the program works fine and the last loop will break only after EOF was sent. And a bug somehow make the program's behavior strange in last two cases. If the bug was fixed, then after the first ctrl + D was pressed, the loop will go on without stop and the program will exit. Is that correct? – Page David Jul 31 '18 at 04:50

0 Answers0