You are trying to access the file variable outside the conditional branches where its life is over. When you declare them within the { ... } conditional blocks, it will go out of scope at the closing bracket.
The proper solution would be either to declare it in the beginning of your function outside the scope of the conditional branches, and then open the desired files in the branches, or open only after the conditional block.
I would also consider using the switch statement in this case, rather than continous if/elseif/... as that is what the switch statement is for!
Therefore, your code would be like this (with proper indent, too):
void WriteMatrix(vector<vector<float>> Matrix, float row, float col, int choice)
{
This is the first alternative to be demonstrated and probably the nicest C++ solution:
static const vector<string> filenameLookUpTable{"MultiplyMatrix.txt",
"AddMatrix.txt", "AddMatrix.txt"};
ofstream file(filenameLookUpTable.at(choice-1), ios::app);
You could also do:
ofstream file;
switch(choice) {
case 1:
file.open("MultiplyMatrix.txt", ios::app);
break;
case 2:
file.open("AddMatrix.txt", ios::app);
break;
case 3:
file.open("AddMatrix.txt", ios::app);
break;
}
You could also write this:
string filename;
switch(choice) {
case 1:
filename = "MultiplyMatrix.txt";
break;
case 2:
filename = "AddMatrix.txt";
break;
case 3:
filename = "AddMatrix.txt";
break;
}
ofstream file(filename, ios::app);
and then the end, basically:
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();
}