c ++将printf与wprintf混合(或cout与wcout混合)

Bo *_*sen 10 c++

我知道你不应该将打印与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)

实际上做了诀窍......(注意错误而不是我所期望的那样......),唯一困扰我的是,我不明白为什么以及如何弄明白:-(

Chr*_*fey 6

您应该能够混合它们,但它们通常使用单独的缓冲机制,因此它们相互重叠:

printf("hello world");
cout << "this is a suprise";
Run Code Online (Sandbox Code Playgroud)

可能导致:

hellothis是一个令人惊讶的世界

您没有提供足够的信息来诊断应用程序中printf()的问题,但我怀疑您有多个c运行时(代码中有一个,printf()代码中有一个)并且存在冲突.

  • 但这应该是不太可能的.默认情况下,cout和C的输出流应同步(http://www.cplusplus.com/reference/iostream/ios_base/sync_with_stdio/).在循环中输出大约100次并查看它输出的内容.然后转向同步并再试一次. (2认同)

Mic*_*ker 5

我想你在谈论std::ios_base::sync_with_stdio,但是IIRC它默认开启了.