Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

What happens during the process of cin.get()?

The code is as follows, when I enter "101010^Z000", my output becomes "000". Obviously, my input is invalid after it becomes "^Z". However, why can I continue typing after typing "^Z"? According to the code, shouldn’t it have jumped out of the loop and ended the program at this time? I’m curious.

int main()
{
 const int num = 20;
 int a[num];
 int i = 0;
 while((a[i]=cin.get())!=EOF)
  {
    a[i] = cin.get();
    cout.put(a[i]);
    i++;
  }
 cout << a;
}

like this:

enter image description here

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

And, after this I keep typing "ssss" and the program still outputs "ss" as if the loop is continuing.
enter image description here

>Solution :

Input is usually buffered. There is nothing in C++ that says it must be buffered but usually it is. What this means is that when your program is waiting for input it waits for a whole line of input. That whole line of input goes into a buffer and subsequent reads take characters from the buffer until it is empty. Then the next read will cause the program to wait again, and again it will wait for a whole line of input to be entered.

If you want unbuffered input then I’ve afraid there is no way to get that in standard C++. You have to use platform specific functions for that.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading