C++混合printf和cout

uni*_*x55 2 c++ printf cout

可能重复:
混合cout和printf以获得更快的输出

我正在使用Microsoft Visual Studio 6.0.

以下程序,

#include "stdafx.h"
#include "iostream.h"

int main(int argc, char* argv[])
{
printf("a");
printf("b");
printf("c");
return 0;
}
Run Code Online (Sandbox Code Playgroud)

产生"abc".

而以下方案,

#include "stdafx.h"
#include "iostream.h"

int main(int argc, char* argv[])
{
printf("a");
cout<<"b";
printf("c");
return 0;
}
Run Code Online (Sandbox Code Playgroud)

产生"acb".

有什么问题?我不能在同一个程序中混合使用cout和printf吗?

ybu*_*ill 5

标准说:

当标准iostream对象str同步用标准stdio流f,插入一个字符的效果c

fputc(f, c);
Run Code Online (Sandbox Code Playgroud)

与效果相同

str.rdbuf()->sputc(c);
Run Code Online (Sandbox Code Playgroud)

对于任何字符序列;

默认情况下,除非你调用sync_with_stdio(false),cout与之同步stdout.因此,您的第二个代码段相当于:

printf("a");
fputc(stdout, 'b')
printf("c");
Run Code Online (Sandbox Code Playgroud)

即使在您的实施中也必须产生"abc".

底线:MSVC6不符合标准,这并不奇怪,因为它已经很老了.

  • @ H2CO3很长一段时间都是如此.现在MS处于视线水平.根据我们的可移植性团队,MS在实现C++ 11方面更快 (2认同)