cout和printf的混用而产生的顺序问题

来源:互联网 发布:json被截断 编辑:程序博客网 时间:2024/05/16 23:38

之前对于cout与printf()混用的结果的认识,源于某年北京赛区某judge的总结。据其称,某队在比赛时某题的输出混用了cout与printf(),结果输出的顺序出错。其把原因归结为一个带缓冲而一个不带缓冲。对此金强提出了置疑,因为stdio.h中定义了像ungetc()这样的函数,其作用是将字符放回到输入流中。可见stdio中也是使用了缓冲的。那么为什么cout与printf()混用会发生问题呢?

下面来做一些试验(环境:g++ (GCC) 3.2.3 (mingw special 20030504-1))。

#include <iostream> using namespace std;

int main() { cout << "aaa"; printf("bbb"); return 0; }

输出为:

aaabbb

没有问题。

如果将程序修改一下:

#include <iostream> using namespace std;

int main() { ios::sync_with_stdio(false); cout << "aaa"; printf("bbb"); return 0; }

输出成了:

bbbaaa

顺序发生了错误。

sync_with_stdio()是在<ios_base>中定义的,当其接受true作为参数时,将会同步iostream与stdio中的流操作。默认是true,因此第一个程序的结果是正确的。然而,尽管C++标准中规定stdio sync标志默认是true,不同平台下的不同编译器可能并不完全支持这个标准。因此也就有了通常意义上的关于“不要混用iostream与stdio”之类的警告。

如果再修改一下程序:

#include <iostream> using namespace std;

int main() { ios::sync_with_stdio(false); cout << "aaa" << flush; printf("bbb"); return 0; }

这回程序的输出就又正确了。因为flush强制清空了缓冲区,将其中的内容输出。

原创粉丝点击