readCSV.cpp 1.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970
  1. // This file is part of libigl, a simple c++ geometry processing library.
  2. //
  3. // Copyright (C) 2013 Alec Jacobson <[email protected]>
  4. //
  5. // This Source Code Form is subject to the terms of the Mozilla Public License
  6. // v. 2.0. If a copy of the MPL was not distributed with this file, You can
  7. // obtain one at http://mozilla.org/MPL/2.0/.
  8. #include "readCSV.h"
  9. #include <sstream>
  10. #include <string>
  11. #include <fstream>
  12. #include <iostream>
  13. #include <vector>
  14. template <typename Scalar>
  15. IGL_INLINE bool igl::readCSV(
  16. const std::string str,
  17. Eigen::Matrix<Scalar,Eigen::Dynamic,Eigen::Dynamic>& M)
  18. {
  19. std::vector<std::vector<Scalar> > Mt;
  20. std::ifstream infile(str.c_str());
  21. std::string line;
  22. while (std::getline(infile, line))
  23. {
  24. std::istringstream iss(line);
  25. std::vector<Scalar> temp;
  26. Scalar a;
  27. char ch;
  28. while (iss >> a){
  29. temp.push_back(a);
  30. if(!(iss >> ch))
  31. break;
  32. }
  33. if (temp.size() != 0) // skip empty lines
  34. Mt.push_back(temp);
  35. }
  36. if (Mt.size() != 0)
  37. {
  38. // Verify that it is indeed a matrix
  39. for (unsigned i = 0; i<Mt.size(); ++i)
  40. {
  41. if (Mt[i].size() != Mt[0].size())
  42. {
  43. infile.close();
  44. return false;
  45. }
  46. }
  47. M.resize(Mt.size(),Mt[0].size());
  48. for (unsigned i = 0; i<Mt.size(); ++i)
  49. for (unsigned j = 0; j<Mt[i].size(); ++j)
  50. M(i,j) = Mt[i][j];
  51. // cerr << "TRUE!" << endl;
  52. return true;
  53. }
  54. infile.close();
  55. return false;
  56. }
  57. #ifdef IGL_STATIC_LIBRARY
  58. // Explicit template instantiation
  59. // generated by autoexplicit.sh
  60. #endif