readCSV.cpp 1.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768
  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. std::vector<std::vector<Scalar> > Mt;
  21. std::ifstream infile(str.c_str());
  22. std::string line;
  23. while (std::getline(infile, line))
  24. {
  25. std::istringstream iss(line);
  26. vector<Scalar> temp;
  27. Scalar a;
  28. while (iss >> a)
  29. temp.push_back(a);
  30. if (temp.size() != 0) // skip empty lines
  31. Mt.push_back(temp);
  32. }
  33. if (Mt.size() != 0)
  34. {
  35. // Verify that it is indeed a matrix
  36. for (unsigned i = 0; i<Mt.size(); ++i)
  37. {
  38. if (Mt[i].size() != Mt[0].size())
  39. {
  40. infile.close();
  41. return false;
  42. }
  43. }
  44. M.resize(Mt.size(),Mt[0].size());
  45. for (unsigned i = 0; i<Mt.size(); ++i)
  46. for (unsigned j = 0; j<Mt[i].size(); ++j)
  47. M(i,j) = Mt[i][j];
  48. // cerr << "TRUE!" << endl;
  49. return true;
  50. }
  51. infile.close();
  52. return false;
  53. }
  54. #ifdef IGL_STATIC_LIBRARY
  55. // Explicit template instantiation
  56. // generated by autoexplicit.sh
  57. #endif