为什么这段使用 printf 和 cout 的代码没有预期的输出?

Why doesn't this code using printf and cout have the expected output?

本文关键字:输出 代码 printf 段使用 cout 为什么      更新时间:2023-10-16

我有以下代码:

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 编译器中

对此的一种可能的解释是coutprintf使用单独的缓冲区。 当使用 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::coutprintf,则需要使用:

std::ios_base::sync_with_stdio(true);

std::ios_base::sync_with_stdio(false);

看到它在 http://ideone.com/7sgH2I 工作。

你可能错过了flush() std::coutprintf()对此有不同的行为。此外,还应同步 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;
}

它应该按照您的预期运行。请在此处查看工作演示。