ios::sync_with_stdio()

函数ios::sync_with_stdio()继承自ios_base::sync_with_stdio()。

 

语法如下:

bool sync_with_stdio ( bool sync = true );

 

这个函数使iostream标准流对象和stdio的标准流对象同步。也就是说,他们使用了相同的缓冲区,标志位(如EOF,ERROR)也是同步的。

 

默认这个同步功能是打开的,可以调用sync_with_stdio(false)关闭iostream和stdio的同步。

同步的好处是可以把iostream和cstdio混在一起用,如C++代码调用C库的时候。而坏处就是效率下降了。

 

下面代码可以看出sync_with_stdio()的作用。

#include #include #include using namespace std; int main() { char str1[256], str2[256]; //-----------------------------------------------------------------// //ios::sync_with_stdio(true); ios::sync_with_stdio(true); cout << "ios::sync_with_stdio(true);" << endl; //1. cin和fgets可以混用,cin没读取完的由fgets继续读取。 cout << "cin >> str1: "; cin >> str1; printf("fgets >> str2: "); fgets(str2, 256, stdin); //---- fflush(stdout); cout << endl; //---- //2. 这里cout和printf可以混用,输出顺序和程序一致 cout << "str1: " << str1 << '/n'; printf("str2: %s", str2); //-----------------------------------------------------------------// //ios::sync_with_stdio(false); ios::sync_with_stdio(false); cout << "ios::sync_with_stdio(false);" << endl; //3. 输入缓冲区不同,两次输入互不影响 cout << "cin >> str1: "; cin >> str1; printf("fgets >> str2: "); fgets(str2, 256, stdin); //---- fflush(stdout); cout << endl; //---- //4. 这个时候cout和stdout使用不同的缓冲区,缓冲机制也不同, // 所以输出顺序可能和程序不同。 cout << "str1: " << str1 << '/n'; printf("str2: %s", str2); //------------------------------------------------------------------// cout.flush(); fflush(stdout); printf("end"); getchar(); return 0; }   

输入输出如下(操作系统Win7,编译器DevCpp):

 

 

可以留意到,在第一部分,cin和fgets共同读取了第一次输入的"string1 string2"。

第二部分第一次输入的后半部分" string2"被丢弃,fgets要求重新输入;而输出的时候,cout的输出被推迟了。

 

 

参考链接

http://www.cplusplus.com/reference/iostream/ios_base/sync_with_stdio/

http://publib.boulder.ibm.com/infocenter/zos/v1r9/index.jsp?topic=/com.ibm.zos.r9.cbcpx01/stdwithc.htm

 

 

你可能感兴趣的:(C/C++)