Skip to content

Instantly share code, notes, and snippets.

@yangyushi
Last active April 7, 2022 14:55
Show Gist options
  • Save yangyushi/a196b6d6850a068a43fd591437aec891 to your computer and use it in GitHub Desktop.
Save yangyushi/a196b6d6850a068a43fd591437aec891 to your computer and use it in GitHub Desktop.
Parse .xyz file and load to std::vector
#include <iostream>
#include <fstream>
#include <regex>
#include <string>
using XYZ = std::array<double, 3>;
using Coord3D = std::vector<XYZ>;
int main() {
std::ifstream f;
std::string line;
std::string particle_type;
std::regex head{"\\d+"};
std::smatch matched;
Coord3D coordinates {};
XYZ xyz {0, 0, 0};
double x = 0;
int N = 0;
int total_frame = 0;
f.open("sample_bulk.xyz", std::ios::in);
while (f) {
getline(f, line);
if (regex_match(line, matched, head)){
coordinates.clear();
N = stoi(line);
total_frame += 1;
std::cout << "processing frame " << total_frame;
getline(f, line); // skip the comment line
for (int i = 0; i < N; i++){
getline(f, line); // read line with content [Type x y z]
std::istringstream ss(line);
ss >> particle_type;
for (int j = 0; j < 3; j++){
ss >> x;
xyz[j] = x;
}
coordinates.push_back(xyz);
}
std::cout << " (N = " << coordinates.size() << ")" << std::endl;
}
}
f.close();
}
@yangyushi
Copy link
Author

yangyushi commented May 2, 2020

The format of xyz file is

500
Type, x, y, z
A 6.83552 4.41063 6.6408
...

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment