I have a two .txt files. t1.txt contains two columns with coordinates. t2.txt contains three columns (coordinates and some value). I want to extract a third column from t2.txt for coordinates from t1.txt. Right now my code is looking for the same number in both .txt files. Unfortunately, coordinates are not the same, and I have to find the closest coordinates. How to change my code? I tried to find some information, but I am a very beginner and nothing helps me.
My code:
#include <iostream>
#include <fstream>
#include <iomanip>
using namespace std;
double** alokujPamiec(int,int);
void deleteAlokujPamiec(double**&);
int main()
{
int liczba=0;
fstream plik1("t1.txt",ios::out | ios::in); // 2 columns
fstream plik2("t2.txt", ios::out | ios::in); //3 columns
ofstream plik5("wynik.txt");
plik5 << setprecision(5) << fixed; // precision
int p1=0,p2=0;
char buff[255];
if(plik1.is_open()){
while(plik1.getline(buff,255)){
p1++; // number of lines
}
}else cout <<"Error in opening file 1"<<endl;
if(plik2.is_open()){
while(plik2.getline(buff,255)){
p2++;
}
}else cout <<"Error in opening file 2"<<endl;
cout << "lines in t1.txt" << "\t" <<p1<<endl;
cout << "lines in t2.txt" << "\t" <<p2<<endl;
plik1.close();
plik2.close();
fstream plik3("t1.txt",ios::out | ios::in);
fstream plik4("t2.txt", ios::out | ios::in);
double** dane1 = alokujPamiec(p1, 2);
double** dane2 = alokujPamiec(p2, 3);
int h=1;
cout <<"Loading data...."<<endl;
if(plik4.is_open()){
for(int i=0;i<p2;i++)
{
for(int j=0;j<3;j++){
plik4>>dane2[i][j];
}
}
}else cout << "Error 4"<<endl;
if(plik3.is_open()){
for(int i=0;i<p1;i++)
{
for(int j=0;j<2;j++){
plik3>>dane1[i][j];
}
}
}else cout << "Error 3"<<endl;
cout <<"Comparison and writing... "<<endl;
for(int i=0;i<p1;i++)
{
for(int j=0;j<p2;j++)
{
if(dane1[i][0]==dane2[j][0] && dane1[i][1]==dane2[j][1])
{
plik5<<dane1[i][0]<<"\t"<<dane1[j][1]<<"\t"<<dane2[j][0]<<"\t"<<dane2[i][1]<<"\t"<<dane2[i][2]<<endl;
liczba++;
}
}
}
cout <<"Number of found objects"<<"\t"<<liczba<<endl;
plik3.close();
plik4.close();
plik5.close();
deleteAlokujPamiec(dane1);
deleteAlokujPamiec(dane2);
getchar();
return 0;
}
double ** alokujPamiec(int iloscWierszy, int iloscKolumn)
{
double** tab2d = new double*[iloscWierszy];
double* dumm = new double[iloscWierszy*iloscKolumn];
for ( int i = 0; i < iloscWierszy; i++ )
tab2d[i] = dumm + i*iloscKolumn;
return tab2d;
}
void deleteAlokujPamiec(double**& tab2d) {
delete [] tab2d[0];
delete [] tab2d;
tab2d = 0;
}