BPMN-OS
BPMN for optimization and simulation
Loading...
Searching...
No Matches
CSVReader.cpp
Go to the documentation of this file.
1#include "CSVReader.h"
2#include "Keywords.h"
3#include <sstream>
4#include <fstream>
5#include <filesystem>
6#include <strutil.h>
7
8using namespace BPMNOS;
9
10CSVReader::CSVReader(const std::string& instanceFileOrString)
11 : instanceFileOrString(instanceFileOrString)
12{
13}
14
16 std::unique_ptr<std::istream> input;
17
18 if (instanceFileOrString.contains("\n")) {
19 // parameter contains linebreak, assume that it is the csv content
20 input = std::make_unique<std::istringstream>(instanceFileOrString);
21 }
22 else {
23 // parameter contains no linebreak, assume that it is a filename
24 auto fileStream = std::make_unique<std::ifstream>(instanceFileOrString);
25 if (!fileStream->is_open()) {
26 throw std::runtime_error("CSVReader: Could not open file " + instanceFileOrString);
27 }
28 input = std::move(fileStream);
29 }
30
31 Table table;
32
33 std::string line;
34 while (std::getline(*input, line)) {
35 line = encodeCollection( encodeQuotedStrings( line ) );
36 strutil::trim(line);
37//std::cerr << "Line: " << line << std::endl;
38 if ( line.empty() ) continue; // skip empty lines
39 auto cells = strutil::split_any( line, ",;\t" );
40 Row row;
41 for ( auto cell : cells ) {
42 strutil::trim(cell);
43 if ( !cell.empty() && (std::isdigit( cell[0] ) || cell[0] == '.' || cell[0] == '-') ) {
44 // treat cell as number
45 row.push_back((BPMNOS::number)std::stod(cell));
46 }
47 else if ( cell == Keyword::True ) {
48 row.push_back((BPMNOS::number)1);
49 }
50 else if ( cell == Keyword::False ) {
51 row.push_back((BPMNOS::number)0);
52 }
53 else {
54 // treat cell as string
55 row.push_back(cell);
56 }
57 }
58 table.push_back(row);
59 }
60
61 return table;
62}
std::vector< Row > Table
Definition CSVReader.h:17
const std::string instanceFileOrString
Definition CSVReader.h:21
CSVReader(const std::string &instanceFileOrString)
Definition CSVReader.cpp:10
std::vector< std::variant< std::string, BPMNOS::number > > Row
Definition CSVReader.h:16
const std::string False
Definition Keywords.h:8
const std::string True
Definition Keywords.h:9
std::string encodeQuotedStrings(std::string text)
std::string encodeCollection(std::string text)
Function to replace a collection that is not preceded by an alphanumeric or underscore.
BPMNOS_NUMBER_TYPE number
Definition Number.h:42