Stan  1.0
probability, sampling & optimization
 All Classes Namespaces Files Functions Variables Typedefs Enumerator Friends Macros Pages
csv_writer.hpp
Go to the documentation of this file.
1 #ifndef __STAN__IO__CSV_WRITER_HPP__
2 #define __STAN__IO__CSV_WRITER_HPP__
3 
4 #include <ostream>
5 #include <stan/math/matrix.hpp>
6 
7 namespace stan {
8 
9  namespace io {
10 
19  class csv_writer {
20  private:
21  std::ostream& o_;
22  bool at_bol_;
23 
24  public:
25 
32  void comma() {
33  if (at_bol_) {
34  at_bol_ = false;
35  return;
36  }
37  o_ << ",";
38  }
39 
40 
47  csv_writer(std::ostream& o)
48  : o_(o), at_bol_(true) {
49  }
50 
59  void newline() {
60  o_ << "\n";
61  at_bol_ = true;
62  }
63 
72  void write(int n) {
73  comma();
74  o_ << n;
75  }
76 
85  void write(double x) {
86  comma();
87  o_ << x;
88  }
89 
98  void write(const Eigen::Matrix<double,Eigen::Dynamic,1>& v) {
100  for (size_type i = 0; i < v.size(); ++i)
101  write(v[i]);
102  }
103 
112  void write(const Eigen::Matrix<double,1,Eigen::Dynamic>& rv) {
114  for (size_type i = 0; i < rv.size(); ++i)
115  write(rv[i]);
116  }
117 
126  void write(const Eigen::Matrix<double,Eigen::Dynamic,Eigen::Dynamic>& m) {
128  for (size_type i = 0; i < m.rows(); ++i)
129  for (size_type j = 0; j < m.cols(); ++j)
130  write(m(i,j));
131  }
132 
141  void write_col_major(const Eigen::Matrix<double,Eigen::Dynamic,Eigen::Dynamic>& m) {
143  for (size_type j = 0; j < m.cols(); ++j)
144  for (size_type i = 0; i < m.rows(); ++i)
145  write(m(i,j));
146  }
147 
157  void write(const std::string& s) {
158  comma();
159 
160  o_ << '"';
161  for (size_t i = 0; i < s.size(); ++i) {
162  if (s.at(i) == '"') {
163  o_ << '"' << '"'; // double quotes
164  } else {
165  o_ << s.at(i);
166  }
167  }
168  o_ << '"';
169  }
170 
171 
172  };
173 
174  }
175 
176 }
177 
178 #endif

     [ Stan Home Page ] © 2011–2012, Stan Development Team.