Skip to content

Commit 27a0f28

Browse files
Create csv.cc
1 parent e72b630 commit 27a0f28

File tree

1 file changed

+79
-0
lines changed

1 file changed

+79
-0
lines changed

example/csv.cc

Lines changed: 79 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,79 @@
1+
/*
2+
csv.cc
3+
MIT License [email protected]
4+
*/
5+
#include <peglib.h>
6+
#include <iostream>
7+
#include <cstdlib>
8+
#include <vector>
9+
#include <cctype>
10+
#include <fstream>
11+
12+
int col,row;
13+
std::vector<std::string> a;
14+
void push(std::string m){
15+
16+
a.push_back(m);
17+
}
18+
void failClue(int col){
19+
std::cout << "failed at col "<<col<<" row "<<row<<"\nError token:";
20+
for (int ss=0;ss<a.size();++ss){
21+
std::cout << a.at(ss);
22+
}
23+
std::cout <<std::endl;
24+
for (int c=0;c<col;++c){
25+
std::cout <<" ";
26+
if (c==(col-1)){
27+
std::cout <<"^";
28+
}
29+
}
30+
}
31+
int main(int argc, const char** argv)
32+
{
33+
34+
if (argc < 2 || std::string("--help") == argv[1]) {
35+
std::cout << "usage: "<<argv[0]<<" [input]" << std::endl;
36+
return 1;
37+
}
38+
std::string line,content;
39+
std::ifstream file(argv[1]);
40+
auto syntax = R"(
41+
FILE <- HDR ROW+
42+
HDR <- ROW
43+
ROW <- QUOTED STRING QUOTED (COMMA QUOTED STRING QUOTED)* _?
44+
_ <- ' ' / '\t' / '\r' / [ \t\r\n]+
45+
STRING <- < [ a-z,-_.A-Z0-9]+ >
46+
COMMA <- ','
47+
QUOTED <- '"'
48+
)";
49+
row=0;
50+
peglib::peg pg(syntax);
51+
pg["FILE"] = []( const std::vector<peglib::any>& v){
52+
};
53+
pg["ROW"] = [](const char *s,size_t l, const std::vector<peglib::any>& v) mutable{
54+
++row;
55+
col=l;
56+
push(std::string(s,l));
57+
};
58+
if (!file.is_open()) {
59+
perror("error while opening file"); file.close();
60+
}
61+
while(std::getline(file, line)) {
62+
content+=line;
63+
}
64+
65+
auto ret = pg.parse(content.c_str());
66+
std::cout <<std::boolalpha << ret<<"\n";
67+
if (!ret){
68+
failClue(col);
69+
}
70+
file.close();
71+
return 0;
72+
}
73+
74+
file.csv
75+
76+
"04.1.00003","Da2d3d1,2","DAD.02"
77+
"04.2.00003","D a2d3d12","DAD_.,0-3"
78+
"04.3.00003","Da2d 3d1,2","DAD02"
79+
I hope this can be useful for other poeple for starting point.

0 commit comments

Comments
 (0)