I am used to writing programs in Fortran (this is f90), but I need to write a program in C++. I am very confused on how to pass a multidimensional array from a C++ function. To give an example, I want to read a list of atomic coordinates in XYZ format in a subroutine and then pass the coordinates to the main program.
Here it is in Fortran:
program findcenterofmass
character*2 atm(1000)
integer ttl
real*8 crd(1000,3)
call getxyz(atm,ttl,crd)
call centerofmass(ttl,crd)
end
subroutine getxyz(element,atomcount,coord)
character*2 element(1000)
integer atomcount
real*8 coord(1000,3)
open(file='test.xyz',unit=1)
read(1,*) atomcount
read(1,*)
do i=1,atomcount
read(1,*) element(i),(coord(i,j),j=1,3)
enddo
close(unit=1)
end
subroutine centerofmass(atomcount,coord)
integer atomcount
real*8 coord(1000,3)
real*8 x,y,z
do i=1,atomcount
x=x+coord(i,1)/atomcount
y=y+coord(i,2)/atomcount
z=z+coord(i,3)/atomcount
enddo
write(*,*) 'Center of mass is x: ',x,' y:',y,' z:',z
end
The test file read here is a very simple CO2 molecule:
3
C 0.0 0.0 0.0
O -1.4 0.0 0.0
O 1.4 0.0 0.0
So I need to do this same procedure in C++ and the part that seems most confusing is reading the coordinates into a multidimensional array and then passing the array back to the main program.
Here's the C++ (this has errors) -- Any help would be greatly appreciated!
#include <stdio.h>
#include <iostream>
#include <string>
#include <sstream>
void readxyz(double& x);
int main () {
double x[100][3];
readxyz(double& x);
std::cout << " x " << x[0][0] << "\n";
return 0;
}
void readxyz(double& coord[][3])
{
int i,j,k;
int ttl;
int MAXATOM=1000;
int MAXLINE=72;
char atoms[MAXATOM][2];
long double coord[MAXATOM][3];
char s[MAXLINE];
const char* filename="test.xyz";
using namespace std;
cout.precision(12);
FILE *fp = fopen(filename,"r");
fgets(s,MAXLINE,fp);
std::stringstream stream(s);
stream >> ttl;
fgets(s,MAXLINE,fp);
for (i = 0; i < ttl; i++) {
fgets(s,MAXLINE,fp);
std::stringstream stream(s);
stream >> atoms[i] >> coord[i][0] >> coord[i][1] >> coord[i][2];
}
}