简体   繁体   中英

need help understanding cin buffer behavior

The code below shows the output as

 enter something abc you entered: a you entered: b you entered: c 
  #include "stdafx.h"
    #include <iostream>

    using namespace std;

    int _tmain(int argc, _TCHAR* argv[])
    {
    char c;

    while(cin>>c)
    {
    //Do something  
        cout<<"you entered: "<<c<<"\n";
    }


    return 0;
    }

why is it not showing only the first character entered? I know I can force it to ignore the cin buffer after first char by using

cin.ignore(1,'\\n')

but shouldnt it only ready one character and ignore the rest?

Your code says while (cin >> c) doStuff . That is: as long as there are characters to be read, doStuff. So the program is doing exactly that. Did you perhaps mean if (cin >> c) ?

... but shouldnt it only ready one character and ignore the rest?

No. It works correctly and I do not know where you got the idea that it should ignore something. It reads whatever is there in the buffer, and blocks waiting for more input iff the buffer is empty. In your case it gets empty only after three iterations of the while loop.

cin can only process the input from the keyboard once the RETURN key has been pressed. The while loop continued the operation till all the characters in the cin buffer gets printed one by one.

So is the program behaves.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM