Last active
April 7, 2022 14:55
-
-
Save yangyushi/a196b6d6850a068a43fd591437aec891 to your computer and use it in GitHub Desktop.
Parse .xyz file and load to std::vector
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#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(); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
The format of
xyz
file is