尽管包含了<iostream>,仍无法创建std::ofstream变量。

40

我在C++中遇到了ofstream错误,这是我的代码:

int main () {
  ofstream myfile;
  myfile.open ("example.txt");
  myfile << "Writing this to a file.\n";
  myfile.close();
  return 0;
}

Dev-C++ 10的错误

C:\devp\main.cpp 聚合 `std::ofstream OutStream' 类型不完整,无法定义

提前致谢

7个回答

69

您可以尝试这个:

#include <fstream>

int main () {
  std::ofstream myfile;

  myfile.open ("example.txt");
  myfile << "Writing this to a file.\n";
  myfile.close();

  return 0;
}

33
文件流实际上是在<fstream>中定义的。

7
您可能没有包含适当的头文件。
在您的源文件开头添加#include <fstream>应该可以解决这个错误。

2

可能是您引入了错误的头文件。有一个名为<iosfwd>的头文件,用于需要引用STL类型但不需要完整声明该类型的头文件。您仍然需要包含正确的头文件<iostream>才能使用相关的类型。


0

只需包含fstream头文件即可。因为ofstreamifstream已经包含在fstream中。


-1

添加#include <fstream>

代码:

#include <iostream>
#include <fstream>

using namespace std;

int main() {

    std::ofstream myfile;
    myfile.open("example.txt", std::ios::out);
    myfile << "Writing this to a file\n";
    myfile.close();

    return 0;
}

请正确格式化您的代码并查看:为什么“using namespace std;”被认为是不良实践? - Adrian Mole

-2
我遇到了同样的错误,因为我忘记在包含它后使用using namespace std;,问题得到了解决。

忘记使用 std 会导致编译错误而不是运行时错误。 - Abhinav Singh

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接