-2

Inserting an string using cin.getline() and want to print that string on console using cout.write().Prints the entered string after I quit the application

#include<iostream.h>
#include<conio.h>
int main() {
char str[20];
cout<<"Enter a string:";
cin.getline(str,20);
cout<<"Entered string:";
cout.write(str,20);
cout.flush();
getch();
return 0;
}

2 Answers2

0

Output to streams is usually buffered. Unless the buffer is flushed (which happens when you fill the buffer completely, or explicitly flush it) then the output won't actually be written.

The stream buffer is also flushed when the stream object is closed, which happens when std::cout is destructed as part of program termination. That's why you see the output when the program exits.

So the solution is simple: Explicitly flush the buffer (using e.g. std::cout.flush();) after each write.

Some programmer dude
  • 400,186
  • 35
  • 402
  • 621
0

std::ostreamimplementations like std::cout work buffered usually. That means the std::ostream implementation collects what's passed with calls to write() in a buffer, and only if the buffer is exhausted, the actual contents will be sent to the physical device (a terminal, or a file manifested at the storage).

To trigger the stream writing the buffer contents to the terminal or a file, you explicitely have to call std::ostream::flush() (note that the std::endl I/O manipulator does that implicitely).

πάντα ῥεῖ
  • 1
  • 13
  • 116
  • 190