问题
Possible Duplicate:
mixing cout and printf for faster output
I'm using Microsoft Visual Studio 6.0.
The following program,
#include "stdafx.h"
#include "iostream.h"
int main(int argc, char* argv[])
{
printf("a");
printf("b");
printf("c");
return 0;
}
produces "abc".
While the following program,
#include "stdafx.h"
#include "iostream.h"
int main(int argc, char* argv[])
{
printf("a");
cout<<"b";
printf("c");
return 0;
}
produces "acb".
What's the problem? Can't I mix cout and printf in the same program?
回答1:
The standard says that:
When a standard iostream object
str
is synchronized with a standard stdio streamf
, the effect of inserting a characterc
byfputc(f, c);
is the same as the effect of
str.rdbuf()->sputc(c);
for any sequences of characters;
By default, unless you invoke sync_with_stdio(false)
, cout
is synchronized with stdout
. Therefore your second code snippet is equivalent to:
printf("a");
fputc(stdout, 'b')
printf("c");
Which must produce "abc" even on your implementation.
Bottom line: MSVC6 is not standard conforming, which is not a surprise as it is very old.
来源:https://stackoverflow.com/questions/13667397/c-mixing-printf-and-cout