为什么这段使用 printf 和 cout 的代码没有预期的输出?
Why doesn't this code using printf and cout have the expected output?
我有以下代码:
int main ()
{
ios_base::sync_with_stdio(false);
cin.tie(NULL);
for (int i = 0; i < 3; i++) {
cout << i << " ";
printf("%d ", i);
}
cout << endl;
return 0;
}
这段代码的预期输出是:
0 0 1 1 2 2
但是,它会打印:
0 1 2
0 1 2
此问题发生在 GNU G++ 4.9.2 编译器中
您可能会错过 flush()
std::cout
。 printf()
对此有不同的行为。还应该同步 IO 缓冲区。如果您将代码更改为
int main () {
ios_base::sync_with_stdio(true); // Synchronizing the IO buffers
// must be enabled
cin.tie(NULL);
for (int i = 0; i < 3; i++) {
cout << i << " ";
cout.flush(); // <<<<<<<<<<
printf("%d ", i);
}
cout << endl;
return 0;
}
它应该会像您预期的那样运行。请查看工作演示 here。
如果您希望同步输出 std::cout
和 printf
,您需要使用:
std::ios_base::sync_with_stdio(true);
没有
std::ios_base::sync_with_stdio(false);
查看它在 http://ideone.com/7sgH2I 的工作情况。
一个可能的解释是 cout
和 printf
使用不同的缓冲区。 cout
在使用 endl
命令刷新时或缓冲区已满(通常为 512 字节)时在终端屏幕上输出。
我不确定 printf
(如果我错了,请随时纠正我),但它也遵循类似的行为。所以发生的事情是在程序结束时,两个缓冲区都被刷新,所以你看到的输出就实现了。
我运行我机器上的代码(GCC 4.8.1)以及如下修改
cout << i << " . ";
printf("%d ", i);
我观察到的输出是 0 1 2 0 . 1 . 2 .
,这似乎表明在我的情况下 printf 首先刷新。我不知道这是设计使然(在标准中某处提到),还是取决于上下文。
试试这个
cout << i << " " <<std::flush;
printf("%d ", i);
fflush(stdout);
默认情况下,C stdio 函数 printf 等和 C++ io 流是同步的,这意味着它们可以互换使用。在代码的开头,您已经删除了与 ios_base::sync_with_stdio(false)
的同步,不确定您的实际意图是否是编写此同步两个 io 库的 ios_base::sync_with_stdio(true)
。
我有以下代码:
int main ()
{
ios_base::sync_with_stdio(false);
cin.tie(NULL);
for (int i = 0; i < 3; i++) {
cout << i << " ";
printf("%d ", i);
}
cout << endl;
return 0;
}
这段代码的预期输出是:
0 0 1 1 2 2
但是,它会打印:
0 1 2
0 1 2
此问题发生在 GNU G++ 4.9.2 编译器中
您可能会错过 flush()
std::cout
。 printf()
对此有不同的行为。还应该同步 IO 缓冲区。如果您将代码更改为
int main () {
ios_base::sync_with_stdio(true); // Synchronizing the IO buffers
// must be enabled
cin.tie(NULL);
for (int i = 0; i < 3; i++) {
cout << i << " ";
cout.flush(); // <<<<<<<<<<
printf("%d ", i);
}
cout << endl;
return 0;
}
它应该会像您预期的那样运行。请查看工作演示 here。
如果您希望同步输出 std::cout
和 printf
,您需要使用:
std::ios_base::sync_with_stdio(true);
没有
std::ios_base::sync_with_stdio(false);
查看它在 http://ideone.com/7sgH2I 的工作情况。
一个可能的解释是 cout
和 printf
使用不同的缓冲区。 cout
在使用 endl
命令刷新时或缓冲区已满(通常为 512 字节)时在终端屏幕上输出。
我不确定 printf
(如果我错了,请随时纠正我),但它也遵循类似的行为。所以发生的事情是在程序结束时,两个缓冲区都被刷新,所以你看到的输出就实现了。
我运行我机器上的代码(GCC 4.8.1)以及如下修改
cout << i << " . ";
printf("%d ", i);
我观察到的输出是 0 1 2 0 . 1 . 2 .
,这似乎表明在我的情况下 printf 首先刷新。我不知道这是设计使然(在标准中某处提到),还是取决于上下文。
试试这个
cout << i << " " <<std::flush;
printf("%d ", i);
fflush(stdout);
默认情况下,C stdio 函数 printf 等和 C++ io 流是同步的,这意味着它们可以互换使用。在代码的开头,您已经删除了与 ios_base::sync_with_stdio(false)
的同步,不确定您的实际意图是否是编写此同步两个 io 库的 ios_base::sync_with_stdio(true)
。