Jun 13, 2011 at 9:00pm UTC
i am a beginner in c + + and need to simplify this program. and i will prefer to use
cout << "Enter the name of an existing text file: ";
cin.get (str,256);
iFile.open (str); // open file
Thanks:
#include <cstdlib>
#include <iostream>
#include <fstream>
#include <sstream>
#include <vector>
#include <fstream>
#include <string>
#include <cmath>
#include <iomanip>
using namespace std;
int matrix_lines(istream &iFile) {
// Método para obtener el número lineas de la matriz.
iFile.clear();
iFile.seekg(0);
int lines = 0;
string line;
while(!iFile.eof()) {
getline (iFile, line);
lines++;
}
cout << "Numero de lineas: " << lines-1 << endl;
return lines-1;
}
int matrix_cols(istream &iFile) {
// Método para obtener el número de columnas de la matriz.
iFile.clear();
iFile.seekg(0);
string line;
double n;
int cols = 0;
getline (iFile, line);
stringstream is(line);
n = 0;
while (is >> n) {
cols++;
}
cout << "Numero de columnas: " << cols << endl;
return cols;
}
double** read_file(std::string filename,int lines,int cols)
{
std::ifstream file;
file.open("pf.txt", std::ios::in);
if(!file.is_open()){return 0;}
std::ofstream file2;
file2.open("pf2.txt", std::ios::out);
if(!file2.is_open()){return 0;}
double ae, H, a, o, ah;
long double ad, n;
double** data = new double*[cols+1];
for(int i = 0; i <cols;++i){ data[i] = new double[lines+1]; }
//read each row
for(int i =0;i<lines;++i)
{
for(int j =0;j<cols;++j)//push into the col
{ file >>data[j][i]; }
a=(data[0][i] + data[2][i]/3600.0);
o=(data[3][i]+(data[0][i]/60.0));
ae= (data[2][i]);
H= (data[3][i]);
ah= (data[0][i] - data[1][i]);
ad= ((4.23568 / 180.0)*(lat));
n= (633659.0 / sqrt(1.0 -
0.00669438235683*(pow(sin(rad),2))));
{ file2 << a <<"\t"<< o <<"\t" <<
ae<<"\t"<< H<<"\t"<<
ah<<"\t"<< n;}
file2 << "\n";
}
file.close();
file2.close();
return data;
}
int main(int argc, char** argv) {
int lines,cols;
ifstream iFile;
iFile.open("pf.txt");
if(!iFile) { // file couldn't be opened
cerr << "Error: file could not be opened" << endl;
exit(1);
}
cols = matrix_cols(iFile);
lines = matrix_lines(iFile);
vector<vector<double> > matrix;
matrix.resize(cols);
for(int i = 0; i < cols; i++)
matrix[i].resize(lines);
iFile.close();
double** data;
if( !(data = read_file("test",lines,cols) ) ){return 0;}
system("pause");
return 0;
}