From 7fa4894cc3f3f0f46f7541d695cdfc2c4ebe89ec Mon Sep 17 00:00:00 2001 From: Mark Liversedge Date: Fri, 7 Apr 2017 10:58:38 +0100 Subject: [PATCH] BodyMeasures Handle ',' embedded in string .. needs to be tested ! --- src/FileIO/BodyMeasuresCsvImport.cpp | 8 ++-- src/FileIO/BodyMeasuresCsvImport.h | 55 ++++++++++++++++++++++++++++ 2 files changed, 59 insertions(+), 4 deletions(-) diff --git a/src/FileIO/BodyMeasuresCsvImport.cpp b/src/FileIO/BodyMeasuresCsvImport.cpp index bf3cb5e8b..baca4ee5d 100644 --- a/src/FileIO/BodyMeasuresCsvImport.cpp +++ b/src/FileIO/BodyMeasuresCsvImport.cpp @@ -55,8 +55,8 @@ BodyMeasuresCsvImport::getBodyMeasures(QString &error, QDateTime from, QDateTime emit downloadStarted(100); // get headers first / and check if this is a body measures file - QString headerLine= QString(file.readLine()); - QStringList headers = headerLine.split(","); + CsvString headerLine= QString(file.readLine()); + QStringList headers = headerLine.split(); // remove whitespaces from strings QMutableStringListIterator iterator(headers); while (iterator.hasNext()) { @@ -94,9 +94,9 @@ BodyMeasuresCsvImport::getBodyMeasures(QString &error, QDateTime from, QDateTime // all headers are valid, no duplicates and minimal "ts" and "weightkg" exist emit downloadProgress(50); while (!file.atEnd()) { - QString itemLine = QString(file.readLine()); + CsvString itemLine = QString(file.readLine()); lineNo ++; - QStringList items = itemLine.split(","); + QStringList items = itemLine.split(); if (items.count() != headers.count()) { // we only process valid data - so stop here // independent if other items are ok diff --git a/src/FileIO/BodyMeasuresCsvImport.h b/src/FileIO/BodyMeasuresCsvImport.h index 94cb62a48..7d474031b 100644 --- a/src/FileIO/BodyMeasuresCsvImport.h +++ b/src/FileIO/BodyMeasuresCsvImport.h @@ -46,4 +46,59 @@ class BodyMeasuresCsvImport : public QObject { QStringList allowedHeaders; }; + +class CsvString : public QString +{ + public: + CsvString(QString other) : QString(other) {} + + // we just reimplement split, to process "," in a string + QStringList split() { + + enum State {Normal, Quote} state = Normal; + QStringList returning; + QString value; + + for (int i = 0; i < size(); i++) { + QChar current = at(i); + + if (state == Normal) { // Normal state + + if (current == ',') { + // Save field + returning.append(value); + value.clear(); + + } else if (current == '"') state = Quote; + else value += current; + + + } else if (state == Quote) { // In-quote state + + // Another double-quote + if (current == '"') { + + if (i+1 < size()) { + + QChar next = at(i+1); + + // A double double-quote? + if (next == '"') { + value += '"'; + i++; + } + else state = Normal; + } + } + + // Other character + else value += current; + } + } + if (!value.isEmpty()) returning.append(value); + + return returning; +} +}; + #endif