c++ - 没有匹配的函数调用 std::basic_ofstream<char>::write()

标签 c++ qt c++11

<分区>

我正在尝试在这里完成二进制 i/o,但我一直收到这个错误,这是...

no matching function for call to 'std::basic_ofstream<char>::write(int*,unsigned int)'

no matching function for call to 'std::basic_ofstream<char>::write(double*,unsigned int)'

这是我的代码...

#include <iostream>
#include <fstream>
#include <string>

using namespace std;

int main()
{
    int x = 123;
    double fx = 12.34;
    ofstream myfile("filename.dat", ios::out | ios::binary);
    myfile.write(&x, sizeof(x));
    myfile.write(&fx, sizeof(fx));
    myfile.close();
    return 0;
}

我发现其他多个帖子也有同样的情况,但他们的解决方法通常是输入...

ofstream myfile(filename.c_str(), ios::out | ios::binary);

当我尝试多次时,编译器仍然对我尖叫。我正在使用 QT Creator 作为我的 IDE,我已经验证它使用的是 C++11。并且还在 Code::Blocks 中运行相同的代码并得到相同的错误。它不喜欢我传递给它的文件名参数。我认为这与第一个参数是 ofstream open() 的成员函数的 const char 有关吗?!

void open(const char *filename, [int mode], [int prot]);

我在这里不理解/遗漏了什么?

最佳答案

write()是一个输出字符的函数,它不会应用任何格式,你需要自己做格式。

该函数需要 const char*争论。它不会接受指向其他类型的指针,需要先进行转换。

参见 here更多细节。

流运算符 <<如果您希望流格式化您的输出,则更适合。

关于c++ - 没有匹配的函数调用 std::basic_ofstream<char>::write(),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38487911/

相关文章:

c++ - 我真的需要 Visual Studio 吗

c++ - 如何使用 Visual Studio CppUnitTestFramework 访问我的代码

c++ - Qt 测试当前对象/小部件是否存在

c++ - QLocalServer - 初学者帮助

c++ - 带 Return 键的 Qt Tab 键顺序

c++ - 如何确定 std::type_index 是否对我的编译器是唯一的?

c++ - 在编译时获取 `std::initializer_list` 的大小

c++ - 如何简洁、便携和彻底地播种 mt19937 PRNG?

c++ - 为什么函数被设计成指针?

c++ - 使用 C++ 和 Windows API 以编程方式更改墙纸