文件在编译时未命名类型错误

file does not name a type error on compilation

本文关键字:类型 错误 未命名 编译 文件      更新时间:2023-10-16

我正在尝试使用以下代码写入输出文件。

#include <iostream>
#include <stdio.h>
#include <iomanip>
#include <stack>
#include <vector>
#include <fstream>
using namespace std;
ofstream file;
file.open ("output.txt");
file.close();

当我试图编译时,我得到的错误文件并没有命名一个类型,但我清楚地指出它是在它前面的行上的流。我不确定这里缺少什么。我在论坛上看过如何输出到文件,下面是给出的代码。

file.open ("output.txt");
file.close();

这些语句必须在函数内部。在C++中,oonly声明可以进入全局范围。试试之类的东西

#include <iostream>
#include <stdio.h>
#include <iomanip>
#include <stack>
#include <vector>
#include <fstream>
using namespace std;
int main() {
    ofstream file;
    file.open ("output.txt");
    file.close();
}

它将您的代码放入main函数中,该函数在程序启动时调用。