在进行了一些测试后,我发现它printf比它快得多cout.我知道它依赖于实现,但在我的Linux机器上printf速度提高了8倍.所以我的想法是混合两种打印方法:我想cout用于简单的打印,我打算printf用于生成大量输出(通常在循环中).只要在切换到其他方法之前不忘记刷新,我认为这样做是安全的:
cout << "Hello" << endl;
cout.flush();
for (int i=0; i<1000000; ++i) {
printf("World!\n");
}
fflush(stdout);
cout << "last line" << endl;
cout << flush;
Run Code Online (Sandbox Code Playgroud)
这样好吗?
更新:感谢所有宝贵的反馈.答案摘要:如果你想避免棘手的解决方案,只需简单地不使用endl,cout因为它会隐式刷新缓冲区.请"\n"改用.如果你产生大量输出会很有趣.
我知道你不应该将打印与printf,cout和wprintf,wcout混合,但很难找到一个好的答案为什么以及是否有可能绕过它.问题是我使用一个外部库,用printf打印,我自己使用wcout.如果我做一个简单的例子它工作正常,但从我的完整应用程序它只是不打印printf语句.如果这确实是一个限制,那么会有许多库无法与广泛的打印应用程序一起工作.对此的任何见解都非常受欢迎.
更新:
我把它归结为:
#include <stdio.h>
#include <stdlib.h>
#include <iostream>
#include <readline/readline.h>
#include <readline/history.h>
int main()
{
char *buf;
std::wcout << std::endl; /* ADDING THIS LINE MAKES PRINTF VANISH!!! */
rl_bind_key('\t',rl_abort);//disable auto-complete
while((buf = readline("my-command : "))!=NULL)
{
if (strcmp(buf,"quit")==0)
break;
std::wcout<<buf<< std::endl;
if (buf[0]!=0)
add_history(buf);
}
free(buf);
return 0;
}
Run Code Online (Sandbox Code Playgroud)
所以我想这可能是一个冲动的问题,但它看起来仍然很奇怪,我必须检查它.
更新 - >解决方法:
首先,wprintf出现同样的问题.但我发现添加:
std::ios::sync_with_stdio(false);
Run Code Online (Sandbox Code Playgroud)
实际上做了诀窍......(注意错误而不是我所期望的那样......),唯一困扰我的是,我不明白为什么以及如何弄明白:-(
我需要制作一个计算 cos(x) 的程序,我的问题是,当我使用printf例如 cos(0.2) 是 0.98 但结果是 0.984 并且它没有四舍五入到 2 个数字。
我的代码:
#include <iostream>
#include <math.h>
using namespace std;
int main()
{
float x = 0.2;
cout << "x=" << x << " cos(y) y=" << printf("%.2f", cos(x)) << "\n";
return 0;
}
Run Code Online (Sandbox Code Playgroud)