The
sync_with_stdio() function allows you to interleave C standard streams with standard streams from either the Standard
C++ Library or the USL I/O Stream Class Library. A call to
sync_with_stdio() does the following:
- cin, cout, cerr, and clog are initialized with stdiobuf objects associated with stdin, stdout, and stderr.
- The flags unitbuf and stdio are set for cout, cerr, and clog.
This ensures that subsequent standard streams may be mixed on a per-character basis. However, a runtime performance penalty is incurred to ensure this synchronization. Figure 1 shows an example program and the output that it produces.
Figure 1. Interleaving I/O with sync_with_stdio()//
// Example of interleaving USL I/O with sync_with_stdio()
//
// tsyncws.cxx
#include <stdio.h>
#include <fstream.h>
int main() {
ios::sync_with_stdio();
cout << "object: to show that sync_with_stdio() allows interleaving\n "
" standard input and output on a per character basis\n" << endl;
printf( "line 1 ");
cout << "rest of line 1\n";
cout << "line 2 ";
printf( "rest of line 2\n\n");
char string1[80] = "";
char string2[80] = "";
char string3[80] = "";
char* rc = NULL;
cout << "type the following 2 lines:\n"
"hello world, here I am\n"
"again\n" << endl;
|
cin.get(string1[0]);
string1[1] = getchar();
cin.get(string1[2]);
cout << "\nstring1[0] is \'" << string1[0] <<
"\'\n"
<< "string1[1] is \'" << string1[1] <<
"\'\n"
<< "string1[2] is \'" << string1[2] <<
"\'\n" << endl;
cin >> &string1[3];
rc = gets(string2); // note: reads to end of line, so
cin >> string3; // this line waits for more input
cout << "\nstring1 is \"" << string1 << "\"\n"
<< "string2 is \"" << string2 << "\"\n"
<< "string3 is \"" << string3 << "\"\n" <<
flush;
}
// sample output (with user input shown underlined):
//
// object: to show that sync_with_stdio() allows interleaving
// standard input and output on a per character basis
//
// line 1 rest of line 1
// line 2 rest of line 2
//
// type the following 2 lines:
// hello world, here I am
// again
//
// hello world, here I am
//
// string1[0] is 'h'
// string1[1] is 'e'
// string1[2] is 'l'
//
// again
//
// string1 is "hello"
// string2 is "world, here I am"
// string3 is "again"
|