Create CsvStream class to replace CsvWriter

This commit is contained in:
Jan
2021-03-11 12:43:33 +01:00
parent 9b15afa70e
commit 88b5eefe24
7 changed files with 149 additions and 100 deletions

View File

@ -1,74 +0,0 @@
#include "CsvWriter.h"
#include <sstream>
CsvWriter::CsvWriter(std::ostream& stream)
: m_stream(stream),
m_column_count(0),
m_current_column(0),
m_first_row(true)
{
}
void CsvWriter::WriteColumn(const std::string& value)
{
if (m_current_column++ > 0)
m_stream << ",";
auto containsSeparator = false;
auto containsQuote = false;
for (const auto& c : value)
{
if (c == '"')
{
containsQuote = true;
break;
}
if (c == SEPARATOR)
containsSeparator = true;
}
if (containsQuote)
{
std::ostringstream str;
for (const auto& c : value)
{
if (c == '"')
str << "\"\"";
else
str << c;
}
m_stream << "\"" << str.str() << "\"";
}
else if (containsSeparator)
{
m_stream << "\"" << value << "\"";
}
else
{
m_stream << value;
}
}
void CsvWriter::NextRow()
{
if (m_first_row)
{
m_first_row = false;
m_column_count = m_current_column;
}
else
{
while (m_current_column < m_column_count)
{
m_stream << ",";
m_current_column++;
}
}
m_stream << "\n";
m_current_column = 0;
}

View File

@ -1,20 +0,0 @@
#pragma once
#include <string>
#include <ostream>
class CsvWriter
{
static constexpr char SEPARATOR = ',';
std::ostream& m_stream;
unsigned m_column_count;
unsigned m_current_column;
bool m_first_row;
public:
explicit CsvWriter(std::ostream& stream);
void WriteColumn(const std::string& value);
void NextRow();
};