gpt4 book ai didi

c++ cout 而不是 fstream

转载 作者:塔克拉玛干 更新时间:2023-11-03 01:53:01 25 4
gpt4 key购买 nike

通常我生活在 C# 的守卫世界中。但有时我不得不出去做点事情。

目前我必须对音频流进行解码,并且必须将其直接输出到我的 C++ 控制台应用程序中。

如果我将内容写入文件,我可以听到正确的结果。但是,如果我使用而不是 fstream cout,我只会听到嘈杂的声音。

我该怎么做才正确?这里是工作文件流代码:

fstream wavefile;
wavefile.open(output, ios::out | ios::binary | ios::trunc);

//do something
wavefile.write((char*) &waveheader, waveheadersize);
//do something else
do {
//do something
//decodedBuffer is of type BYTE* , decodedLength is of type DWORD
wavefile.write((char*) decodedBuffer, decodedLength);
wavefile.flush();
} while (encodedLength > 0);

我不工作的 cout 代码:

std::cout.setf(ios::out | ios::binary | ios::trunc);

//do something
//this works, I got the same output
cout << structToString(&waveheader) << endl;
//do something else
do {
//do something
cout << (char *)decodedBuffer;
} while (encodedLength > 0);

提前致谢

最佳答案

首先,绝对没有理由为 std::fstreamstd::cout 使用不同的代码(除此之外,您的 cout-代码使用格式化输出,错误):

在这两种情况下,您都在使用他们的 ostream 接口(interface)。

因此,首先,通过将第二个代码替换为第一个代码来修复第二个代码(尽可能)。


现在,我们得出一个区别(您试图用 setf 掩盖):std::cout 处于文本模式,而不是二进制模式!

不幸的是,ios::outios::binaryios::trunc 都不是格式化标志,因此您不能用 setf 设置它们.

实际上,事后根本无法更改模式(至少不可移植)。

幸运的是,您可以简单地忽略许多系统上的错误模式,因为 Linux 和其他系统将文本模式和二进制模式等同起来。在 Windows 上,这个黑客应该让你绕过它:

cout.flush();
fflush(stdout);
_setmode(_fileno(stdout), _O_BINARY);

关于c++ cout 而不是 fstream,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26616487/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com