c++为什么变量 "file"在我声明时未声明?

标签 c++ variables ofstream undeclared-identifier

<分区>

我正在使用 visual studio 2012 编写普通的 c++,但对于我声明的变量,我一直收到此错误。

1>c:\users\joe\skydrive\documents\c++\consoleapplication2\matracies 1.cpp(182): error C2065: 'file' : undeclared identifier
1>c:\users\joe\skydrive\documents\c++\consoleapplication2\matracies 1.cpp(184): error C2065: 'file' : undeclared identifier

这是我收到错误的函数。

void WriteMatrix(vector<vector<float>> Matrix, float row, float col, int choice)
{
if (choice == 1)
{
    ofstream file("MultiplyMatrix.txt", ios::app);
}
else if (choice == 2)
{
    ofstream file("AddMatrix.txt", ios::app);
}
else if (choice == 3)
{
    ofstream file("AddMatrix.txt", ios::app);
}
for(int i=0; i<row; i++)
{
    for(int j=0; j<col; j++)
    {
        float temp = Matrix[i][j];
        file<<temp<<" ";
    }
    file<<endl;
}
file<<endl;
file.close();
}

最佳答案

正如 Oli 所说,file 仅存在于定义它的 block 中。

您需要在 if 语句之前定义 file。然后使用 file.open 打开所选文件。

并考虑如果选择既不是 1、2 或 3 会发生什么。

关于c++为什么变量 "file"在我声明时未声明?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23326542/

相关文章:

c++ - 如何将 Visual Assist 片段导入 Visual Studio 2017?

c++ - 在 GDB 中打印 int **x

c++ - 堆内存什么时候真正被释放?

ios - 如何比较 float 变量值是否为无限?

c++ - 删除boost归档对象还会删除与其关联的流吗?

c++ - 如果我在 Mac 上使用 ofstream 写入文件,我的文件存储在哪里?

java - Java 中的 dmp 文件?

c - 在方法头中后缀变量类型的星号有何意义?

C 代码似乎放错了用 fscanf 读取的值

C++ 从文件读取到 vector