-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathPrinter.hpp
More file actions
98 lines (95 loc) · 2.12 KB
/
Printer.hpp
File metadata and controls
98 lines (95 loc) · 2.12 KB
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
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
#pragma once
#include <string>
#include <map>
#include <iostream>
#include <cstdio>
typedef std::map<std::string, std::string> PrinterArgument;
class Printer {
public:
void Print(const std::string & strTemplate, const PrinterArgument &oArgument, const char delimiter = '$'){
int iState = 0;
size_t pos = 0;
std::string strResult;
std::string strArgName;
while(pos < strTemplate.length()){
switch(iState){
case 0:
if(strTemplate[pos] == delimiter){
iState = 1;
strArgName.clear();
}else{
strResult.push_back(strTemplate[pos]);
}
break;
case 1:
if(strTemplate[pos] == delimiter){
iState = 0;
if(oArgument.count(strArgName) > 0){
strResult.append(oArgument.at(strArgName));
}
}else{
strArgName.push_back(strTemplate[pos]);
}
break;
}
pos++;
}
this->Print(strResult);
}
void Print(const std::string & str){
this->Write(MakeIndent(m_iDent));
this->Write(str);
this->Write("\n");
}
virtual void Write(const std::string & str) = 0;
void Indent(){
m_iDent+=4;
}
void Outdent(){
m_iDent-=4;
}
static std::string MakeIndent(int iDent) {
std::string str;
str.reserve(iDent);
for(int i=0;i<iDent;i++){
str.push_back(' ');
}
return str;
}
virtual ~Printer(){
}
protected:
int m_iDent = 0;
};
class StringPrinter: public Printer{
public:
StringPrinter():Printer(){
}
virtual void Write(const std::string & str) override{
m_str.append(str);
}
std::string GetResult() const{
return m_str;
}
protected:
std::string m_str;
};
class FilePrinter: public Printer{
public:
FilePrinter(const std::string & str):Printer(){
m_pFile = fopen(str.c_str(), "w+");
}
virtual void Write(const std::string & str) override{
fputs(str.c_str(), m_pFile);
}
std::string GetResult() const{
return m_str;
}
~FilePrinter(){
fclose(m_pFile);
}
protected:
std::string m_str;
private:
FILE * m_pFile;
};