0

It's a program which reads the input character by character, and prints it in the same way. The conceptual doubt I'm having here is that how is the complete string being displayed only on pressing ENTER key, even though std::cout was used on every iteration of taking each character input?

int main()
{
 char c;
 while(1)
 {
     c = cin.get();
     if(cin.eof())
         break;
     else cout << c;
 }
 return 0;
}
Jonathan Leffler
  • 666,971
  • 126
  • 813
  • 1,185
Rupesh
  • 49
  • 6

1 Answers1

0

Lets examine your code:

#include <iostream>
using namespace std;

int main()
{
    char c;
    while (1)
    {
        c = cin.get();
        if (cin.eof())
            break;
        else cout << c;
    }
    return 0;
}

In our first line, we make a char. Then we enter a while loop. cin.get() waits until the user hits enter, then flushes and puts the input into a buffer. cin.get() then returns the first char in the buffer, and removes the char it returned. if (cin.eof()) does not execute, because we did not put a EOF yet. On the next loops, cin.get() grabs the remaining chars in the buffer, and when the buffer is empty, waits for the user to enter more input and hit enter.

std::cin is buffered, so you will not get input instantly.

Also, read on Why is iostream::eof inside a loop condition (i.e. `while (!stream.eof())`) considered wrong?.