My code is written twice for uncomprehensible reasons

前端 未结 6 763
一向
一向 2021-01-24 10:45

This code is written in C++ and for reasons that I don\'t quite understand it is written twice. I would expect that after inputting a random char it would display the char once

6条回答
  •  一整个雨季
    2021-01-24 11:38

    The text 'this will be written twice..' will not necessarily print twice.

    Type 'qwerty' + ENTER and your stream will have "qwerty\n" within and you'll see this output:

    this will be written twice for ununderstandable reasons
    this will be written twice for ununderstandable reasons
    this will be written twice for ununderstandable reasons
    this will be written twice for ununderstandable reasons
    this will be written twice for ununderstandable reasons
    this will be written twice for ununderstandable reasons
    this will be written twice for ununderstandable reasons
    

    Exactly that many as string "qwerty\n" has characters. The problem is that

    cin.get()

    Puts all chars that you type into a stream/buffer (not your letter char) but handles one char every cin.get() invocation.

    When you type 'abcXd' + enter - the program will print above line 3 times and stop on X.

提交回复
热议问题