cppcore
A small, portable C++ core library
Loading...
Searching...
No Matches
CsvReader.h
Go to the documentation of this file.
1/*-----------------------------------------------------------------------------------------------
2The MIT License (MIT)
3
4Copyright (c) 2014-2026 Kim Kulling
5
6Permission is hereby granted, free of charge, to any person obtaining a copy of
7this software and associated documentation files (the "Software"), to deal in
8the Software without restriction, including without limitation the rights to
9use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
10the Software, and to permit persons to whom the Software is furnished to do so,
11subject to the following conditions:
12
13The above copyright notice and this permission notice shall be included in all
14copies or substantial portions of the Software.
15
16THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
17IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
18FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
19COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
20IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
21CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
22-----------------------------------------------------------------------------------------------*/
23#pragma once
24
25#include <vector>
26#include <fstream>
27#include <string>
28#include <sstream>
29
30namespace cppcore {
31
32//-------------------------------------------------------------------------------------------------
38//-------------------------------------------------------------------------------------------------
39class CsvReader {
40public:
42 CsvReader() = default;
43
45 ~CsvReader() = default;
46
50 static std::vector<std::vector<std::string>> readFromFile(const std::string& filepath) {
51 std::vector<std::vector<std::string>> data;
52 std::ifstream file(filepath);
53 std::string line;
54
55 while (std::getline(file, line)) {
56 std::vector<std::string> row;
57 std::string cell;
58 bool inQuotes = false;
59
60 for (char c : line) {
61 if (c == '"') {
62 inQuotes = !inQuotes;
63 } else if (c == ',' && !inQuotes) {
64 row.push_back(cell);
65 cell.clear();
66 } else {
67 cell += c;
68 }
69 }
70 row.push_back(cell); // Add last cell
71 data.push_back(row);
72 }
73 return data;
74 }
75};
76
77} // namespace cppcore
78
CsvReader()=default
Default constructor.
~CsvReader()=default
Default destructor.
static std::vector< std::vector< std::string > > readFromFile(const std::string &filepath)
Read CSV file robustly, handling quoted fields and commas within quotes.
Definition CsvReader.h:50