为什么这段使用 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 编译器中
对此的一种可能的解释是cout
和printf
使用单独的缓冲区。 当使用 endl
命令刷新时,或者如果缓冲区已满(通常为 512 字节),终端屏幕上cout
输出。
我不确定printf
(所以如果我错了,请随时纠正我),但它也遵循类似的行为。因此,在程序结束时,两个缓冲区都被刷新,因此您看到的输出就实现了。
我在我的机器(GCC 4.8.1)上运行了代码以及如下修改
cout << i << " . ";
printf("%d ", i);
我观察到的输出是0 1 2 0 . 1 . 2 .
这似乎表明在我的情况下 printf 首先刷新。我不知道这是设计使然(在标准中的某处提到),还是取决于上下文。
默认情况下,C stdio 函数 printf 等和 C++ io 流是同步的,这意味着它们可以互换使用。在代码开始时,您已经删除了同步,ios_base::sync_with_stdio(false)
不确定您的实际意图是否是编写此同步两个 io 库的ios_base::sync_with_stdio(true)
。
试试这个
cout << i << " " <<std::flush;
printf("%d ", i);
fflush(stdout);
<</div>
div class="answers">如果要同步输出std::cout
和printf
,则需要使用:
std::ios_base::sync_with_stdio(true);
不
std::ios_base::sync_with_stdio(false);
看到它在 http://ideone.com/7sgH2I 工作。
你可能错过了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;
}
它应该按照您的预期运行。请在此处查看工作演示。
相关文章:
- 为什么我的代码在输出中增加了93天
- 为什么在C的循环中使用printf的Rust代码不显示输出,而在C++的循环中显示std::cout
- 在我的代码中,获得最大的Pair Wise产品C++和输出并不总是正确的
- 我无法获取以下代码的输出
- 为什么我的C++程序的程序集输出充满了 .ascii,没有汇编代码?
- 编译并运行后,输出未出现在 Visual Studio 代码中
- VI工作室代码错误无法打开输出文件主.exe
- 代码编译没有任何输出,入门程序
- 与其他编译器相比,相同的代码在工作室Microsoft提供不同的输出
- 可能我知道为什么这段代码没有给出任何输出吗?
- 从排序数组中删除重复项,具有不同代码方式的相同解决方案具有不同的输出
- Clang 给了我符号更改的警告,但代码仍然产生正确的输出
- 为什么这两个版本的代码给出不同的输出
- 以下与指针相关的代码的输出是什么?
- C++和 Python 中的代码相同,但输出不同
- 为什么我的代码块上没有显示输出?
- C++ 高级代码未给出正确的输出
- (C++)分解这个简单的输入/输出代码:
- 错误的输出代码
- 奇怪的输出(代码块codebblocks -16.01mingw-setup.exe)