readCSV.cpp 1.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869
  1. // This file is part of libigl, a simple c++ geometry processing library.
  2. //
  3. // Copyright (C) 2013 Alec Jacobson <alecjacobson@gmail.com>
  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. using namespace std;
  20. using namespace igl;
  21. std::vector<std::vector<Scalar> > Mt;
  22. std::ifstream infile(str.c_str());
  23. std::string line;
  24. while (std::getline(infile, line))
  25. {
  26. std::istringstream iss(line);
  27. vector<Scalar> temp;
  28. Scalar a;
  29. while (iss >> a)
  30. temp.push_back(a);
  31. if (temp.size() != 0) // skip empty lines
  32. Mt.push_back(temp);
  33. }
  34. if (Mt.size() != 0)
  35. {
  36. // Verify that it is indeed a matrix
  37. for (unsigned i = 0; i<Mt.size(); ++i)
  38. {
  39. if (Mt[i].size() != Mt[0].size())
  40. {
  41. infile.close();
  42. return false;
  43. }
  44. }
  45. M.resize(Mt.size(),Mt[0].size());
  46. for (unsigned i = 0; i<Mt.size(); ++i)
  47. for (unsigned j = 0; j<Mt[i].size(); ++j)
  48. M(i,j) = Mt[i][j];
  49. // cerr << "TRUE!" << endl;
  50. return true;
  51. }
  52. infile.close();
  53. return false;
  54. }
  55. #ifndef IGL_HEADER_ONLY
  56. // Explicit template specialization
  57. // generated by autoexplicit.sh
  58. #endif