C++ mixing printf and cout [duplicate]

£可爱£侵袭症+ 提交于 2021-02-04 19:45:09

问题


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 stream f, the effect of inserting a character c by

fputc(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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!