reading & writing to a file
When I run this program I get the following run time error:
Code:
#include <iostream>
#include <cstdio>
#include <string>
#include <limits>
using namespace std;
class Matrix
{
int row,column;
double** matrix;
public:
Matrix(int,int);
Matrix(int,int,FILE *);//loading matrix from file
~Matrix();
void load_matrix();
void save_matrix();
void show_matrix();
};
Matrix* load_from_file();
Matrix::Matrix(int r,int c):row(r),column(c)
{
matrix=new double*[column];
for(int i=0;i<row;i++)
matrix[i]=new double[row];
for(i=0;i<row;i++)
for(int j=0;j<column;j++)
matrix[i][j]=0;
}
Matrix::Matrix(int r,int c,FILE *fp):row(r),column(c)
{
Matrix::Matrix(r,c);
for(int i=0;i<r;i++)
for(int j=0;j<c;j++)
fread(&matrix[i][j],sizeof(int),1,fp);
fclose(fp);
}
Matrix::~Matrix()
{
for(int i=0;i<row;i++)
delete matrix[i];
delete [] matrix;
}
void Matrix::load_matrix()
{
cout<<"Enter elements:"<<endl;
for(int i=0;i<row;i++)
for(int j=0;j<column;j++)
cin>>matrix[i][j];
}
Matrix* load_from_file()
{
FILE *fp;
string s;
int r,c;
cout<<"Enter file name to load: ";
getline(cin,s);
fp=fopen(s.c_str(),"rb");
if(!fp)
{
cout<<"Error opening file!";
return 0;
}
fread(&r,sizeof(int),1,fp);
fread(&c,sizeof(int),1,fp);
Matrix* pM=new Matrix(r,c,fp);
return pM;
}
void Matrix::save_matrix()
{
string s;
FILE *fp;
cout<<"Enter file name to save!";
getline(cin,s);
fp=fopen(s.c_str(),"wb");
if(!fp)
{
cout <<"error";
return;
}
fwrite(&row,sizeof(int),1,fp);
fwrite(&column,sizeof(int),1,fp);
for(int i=0;i<row;i++)
for(int j=0;j<row;j++)
fwrite(&matrix[i][j],sizeof(int),1,fp);
fclose(fp);
}
void Matrix::show_matrix()
{
cout <<"the following matrix was loaded"<<endl;
for(int i=0;i<row;i++,cout<<endl)
for(int j=0;j<column;j++)
cout<<matrix[i][j]<<" ";
}
int main()
{
int choice;
cout<<"Choose hoe to load matrix"<<endl;
cout<<"1. Load from file!"<<endl<<"2. Enter manualy"<<endl;
do
{
cout<<"Your choice: ";
cin>>choice;
if(cin.fail())
{
cin.clear();
cin.ignore(numeric_limits<int>::max(), '\n');
cout << "\nInput Invalid. Please Try Again: "<<flush;
}
}while(choice !=1 && choice !=2);
if(choice==1)
{
Matrix *pk=load_from_file();
pk->show_matrix();
}
else
{
int r,c;
cout<<"Enter number of rows an columns!";
cin>>r;
cin>>c;
Matrix m(r,c);
m.load_matrix();
m.show_matrix();
//m.save_matrix(); causing run-time error
}
}
Debug assertion failed ....
File fopen.c
line:55
Expression *file !=_T('\0');
Same thing happens when I choose choice 1 in programs menu
I don't know what is causing error. I know that is when I try to open file (just before that line).
Maybe use of string an c_str() in fopen
is bad or something.
Thanks