#include "TwoDArrayWriter.h" #include #include int TwoDArrayWriter::addCol(std::string colName) { assert(!_headersFull); //TODO this part seems broken for reasons I don't understand if (_colsByName.find(colName) != _colsByName.end()) { return -1; } else { _headerRow.push_back(colName); int colNum = _headerRow.size() - 1; _currentRow.push_back(""); _colsByName[colName] = colNum; return colNum; } } void TwoDArrayWriter::addCols(StringList colNames) { for (StringList::iterator it = colNames.begin(); it < colNames.end(); it++) { addCol(*it); } } TwoDArrayWriter::TwoDArrayWriter(const std::string &filename, StringList colNames) : _headersFull (false), _rowInUse(false) { _stream.open(filename.c_str(), std::ios_base::out | std::ios_base::trunc); addCol(""); addCols(colNames); } TwoDArrayWriter::TwoDArrayWriter(const std::string &filename) : _headersFull (false), _rowInUse(false) { _stream.open(filename.c_str(), std::ios_base::out | std::ios_base::trunc); addCol(""); } TwoDArrayWriter::~TwoDArrayWriter() { flushRow(); _stream.close(); } void TwoDArrayWriter::add(std::string const &colHeader, std::string const &rowHeader, std::string const &value) { int column; bool newRow; if (_colsByName.find(colHeader) == _colsByName.end()) { column = addCol(colHeader); } else { column = _colsByName[colHeader]; } if (!_rowInUse || (rowHeader != _currentRow[0])) { if (_rowInUse) flushRow(); _currentRow[0] = rowHeader; newRow = _rowNamesInUse.count(rowHeader) == 0; assert(newRow); _rowNamesInUse.insert(rowHeader); _rowInUse = true; } _currentRow[column] = value; } void TwoDArrayWriter::flushRow() { if(!_headersFull) { writeLine(_headerRow); _headersFull = true; } if (_rowInUse) { writeLine(_currentRow); for(StringList::iterator it = _currentRow.begin(); it < _currentRow.end(); it++) { *it = ""; } _rowInUse = false; } } void TwoDArrayWriter::writeLine(StringList strings) { bool first = true; for(StringList::iterator it = strings.begin(); it < strings.end(); it++) { if (first) first = false; else _stream << ','; _stream << *it; } _stream << std::endl; } bool TwoDArrayWriter::headersFull() { return _headersFull; } #ifdef UNIT_TEST_2D int main() { std::vector< std::string> cols; cols.push_back("ColOne"); cols.push_back("ColTwo"); cols.push_back("ColThree"); TwoDArrayWriter test("2d_test.txt", cols); test.Add("ColOne", "Test1", "00"); test.Add("ColTwo", "Test1", "11"); test.Add("ColOne", "Test2", "22"); test.Add("ColTwo", "Test2", "33"); test.Add("ColThree", "Test2", "44"); cols.clear(); cols.push_back("ColShouldNotWork"); //test.addCols(cols); } #endif