Reading number of lines from file and using it in functions in c++ -
my problem may trivial, don't know how deal it. have program reads matrix file , collects file, displays , performs numeric method on it. when insert number of unknowns(in case equals number of lines in file) cin right. when try read number of lines file , read matrix, display , perform method - although number of lines correctly, program reads matrix if consists of 0. here code of counting lines:
int countlines(ifstream &file){ string line; int l = 0; do{ getline(file, line); l++; }while(!file.eof()); return l;}
and here try use it:
string nameoffile = ""; nameoffile = "matrix1.txt"; ifstream file; file.open(nameoffile.c_str()); if (file.good()==true) { cout <<"the file available<<endl; n = countlines(file); cout << n << endl; collectmatrix(file,n); } else { return 0; } displaymatrix(n);
for example, collectmatrix looks that:
void collectmatrix(ifstream &file, int n){ for(int = 0; <n; i++) { for(int j = 0; j <n; j++) { file>>a[i][j]; //matrix } } for(int k=0; k<n; k++ ) { file>>b[k]; //vector of results } }
and of worked long had cin>>n in code instead of trying read file. , honest, have read file i'm not in programming, i'd thankful hints , help.
ifstream internally keeps track of how far file has read. when countlines method returns, ifstream has read way end of file, , still holds end of file current position in file when pass collectmatrix. when try fill in matrix, there nothing left read file, matrix values not set.
have couple of options fix this. first calculate size of matrix filling in values. code seems indicate matrix square; if so, can determine size of matrix looking @ first line. other, simpler, less efficient approach create second ifstream same file , pass collectmatrix. approach slow, pass through file twice.
Comments
Post a Comment