【问题标题】:error c2065: 'filename' : undeclared identifier错误 c2065:“文件名”:未声明的标识符
【发布时间】:2025-11-23 02:10:01
【问题描述】:
#include <iostream>
#include <ostream>
#include <istream>
#include <ostream>
#include <fstream>
#include <sstream>
#include <string>
#include <iomanip>    


void GetOutputFileStream(std::ofstream * fout, std::string filename);
void PrintStatistics(std::ostream & fout,
    int numUsed,
    int numNew,
    double newTotalPrice,
    double newTotalMileage,
    double usedTotalPrice,
    double usedTotalMileage);


int main()
{

double newTotalPrice = 33333;
double newTotalMileage = 44444;
double usedTotalPrice = 22222;
double usedTotalMileage = 99999;
int numUsed = 2;
int numNew = 3;
std::ofstream fout; // 'f'ile out - fout
std::string filename = "statistics.txt";
GetOutputFileStream(&fout, filename);
// Print to screen
PrintStatistics(std::cout,
    numUsed,
    numNew,
    newTotalPrice,
    newTotalMileage,
    usedTotalPrice,
    usedTotalMileage);
// Print to file
PrintStatistics(fout,
    numUsed,
    numNew,
    newTotalPrice,
    newTotalMileage,
    usedTotalPrice,
    usedTotalMileage);


std::cout << "Press ENTER to continue";
std::cin.get();

return 0;
}

void GetOutputFileStream(std::ofstream * fout, std::string filename)
{
    fout->open(filename, std::ios::out);
}
void PrintStatistics(std::ostream & fout,
int numUsed,
int numNew,
double newTotalPrice,
double newTotalMileage,
double usedTotalPrice,
double usedTotalMileage)
{

}

PrintStatistics 为空,因为我想在开始编写函数之前修复此错误。

我不断收到:错误 C2065:“文件名”:未声明的标识符

但是,每当我尝试测试 GetOutputFileStream(&fout, filename);使用 int main() 中的示例机制确保其功能,如下所示:

std::ofstream fout; // 'f'ile out - fout
std::string filename = "newFile.txt";
GetOutputFileStream(&fout, filename);
fout << "This is my new file!\n";
fout << "This is on a new line!";
fout.close();

我没有收到任何错误,并且该函数的行为与其设想的一样。谁能指出我正确的方向?谢谢。

【问题讨论】:

  • 您在声明之前尝试使用 GetOutputFileStream 和 PrintStatistics。那是你的实际代码吗?
  • Compiles fine 在将GetOutputFileStreamPrintStatistics 放在main() 上方之后。这真的是给你提到的错误的代码吗?
  • 问题是,我提供的示例代码是讲师提供的。我们必须获得与教师使用示例代码相同的输出。是讲师只是将示例代码安排错了,还是我的代码有错误?谢谢!
  • 你现在拥有的代码Compiles Just Fine
  • 不,所有这些都发生在运行时。您(显然)遇到编译错误。它们是无关的。

标签: c++


【解决方案1】:

给你带来麻烦的不是filename。在使用它们之前,您没有定义以下函数:

void GetOutputFileStream(std::ofstream * fout, std::string filename);
void PrintStatistics( ... );

您需要对它们进行原型设计,或在使用它们之前对其进行定义。 See here for more info.

Here are your actual compiler errors.

And here is the same function with one way of fixing them.

【讨论】:

  • 嘿,那是我的错误。我的代码在 main() 之前调用了函数,但我忘记将其包含在我的帖子中。我已经编辑了我的代码。你能再看一遍吗?对不起。
  • @alekbiz 那么你的代码没有问题。您问题中的代码不会产生错误....
  • 我会感谢你的答案,因为你努力帮助我并指导我解决我的问题。
最近更新 更多