I use this own function to split a string into a string vector:
std::vector<std::string> split(char sep, const std::string& str); std::vector<std::string> split(char sep, const std::string& str) { assert(sep != 0 && "PRE: the separator is null"); std::vector<std::string> s; unsigned long int i = 0; for(unsigned long int j = 0; j < str.length(); ++j) { if(str[j] == sep) { s.push_back(str.substr(i, j - i)); i = j + 1; } } s.push_back(str.substr(i, str.size() - i)); return s; }
Then, expecting you to have a Matrix class, you can do something like:
std::string matrices_str; std::ifstream matrix_file(matrix_file_name.c_str()); matrix_file >> matrices_str; const std::vector<std::string> matrices = split('|', matrices_str); std::vector<Matrix<double> > M(matrices.size()); for(unsigned long int i = 0; i < matrices.size(); ++i) { const std::string& matrix = matrices[i]; const std::vector<std::string> rows = split(';', matrix); for(unsigned long int j = 0; j < rows.size(); ++j) { const std::string& row = matrix[i]; const std::vector<std::string> elements = split(',', row); for(unsigned long int k = 0; k < elements.size(); ++k) { const std::string& element = elements[k]; if(j == 0 && k == 0) M[i].resize(rows.size(), elements.size()); std::istringstream iss(element); iss >> M[i](j,k); } } }
Or compressed code:
std::string matrices_str; std::ifstream matrix_file(matrix_file_name.c_str()); matrix_file >> matrices_str; const std::vector<std::string> matrices = split('|', matrices_str); std::vector<Matrix<double> > M(matrices.size()); for(unsigned long int i = 0; i < matrices.size(); ++i) { const std::vector<std::string> rows = split(';', matrices[i]); for(unsigned long int j = 0; j < rows.size(); ++j) { const std::vector<std::string> elements = split(',', matrix[i]); for(unsigned long int k = 0; k < elements.size(); ++k) { if(j == 0 && k == 0) M[i].resize(rows.size(), elements[k].size()); std::istringstream iss(elements[k]); iss >> M[i](j,k); } } }
source share