forked from andy-thomason/read_a_csv_file
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.cpp
45 lines (36 loc) · 891 Bytes
/
main.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
//
// How to read a CSV file.
//
// (C) Andy Thomason 2015
//
// Note CSV files may contain quotes and other complexity, so this
// is not completely general, but it is very simple.
#include <iostream>
#include <fstream>
#include <vector>
int main() {
std::vector<std::string> names;
std::vector<int> score;
std::ifstream is("../test.csv");
if (is.bad()) return 1;
// store the line here
char buffer[2048];
// loop over lines
while (!is.eof()) {
is.getline(buffer, sizeof(buffer));
// loop over columns
char *b = buffer;
for (int col = 0; ; ++col) {
char *e = b;
while (*e != 0 && *e != ',') ++e;
// now b -> e contains the chars in a column
if (col == 0) {
names.emplace_back(b, e);
} else if (col == 1) {
score.push_back(std::atoi(b));
}
if (*e != ',') break;
b = e + 1;
}
}
}