I want to read two matrices from two different txt files, and say output them in another one.
I doesn’t write all of them, it only writes the fist one and “Hi” and stops there.
So I believe it cannot read the second file.
Here is the code:
#include <iostream>
#include <fstream>
using namespace std;
#define I 5
#define J 5
#define P 2
int i,j,k; //for loops
int main ()
{
ifstream inFile;
ofstream outFile;
double C[I][J];
double u[I][J];
double UB = 0;
outFile.open("results.txt");
// READ U0
inFile.open("u.txt", ios::in);
if (! inFile) {
cerr << "unable to open file u.txt for reading" << endl;
return 1;
}
for(i = 0; i < I; i++)
for(j = 0; j < J; j++)
inFile >> u[i][j];
outFile << "u" << endl;
for(i = 0; i < I; i++)
{
for(j = 0; j < J; j++)
outFile << u[i][j];
outFile << endl;
}
outFile << "Hi";
//READ C
inFile.open("C.txt", ios::in);
if (! inFile) {
cerr << "unable to open file C.txt for reading" << endl;
return 1;
}
for(i = 0; i < I; i++)
for(j = 0; j < J; j++)
inFile >> C[i][j];
outFile << "C" << endl;
outFile << "UB=" << UB;
inFile.close();
outFile.close();
return 0;
}
You have two general choices:
inFile1andinFile2, foru.txtandC.txt.inFilewithinFile.close()before trying to use the same variable to open a new file.