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

Time:06-12

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

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

CodePudding user response:

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.

  • Related