StringBuilder

C/C++ code
 
?
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
#ifndef _STRING_BUILDER_H
#define _STRING_BUILDER_H
 
#include "StringElement.h"
#define SB ( StringBuilder() )
 
class StringBuilder {
 
private:
    std::string _value;
 
public:
    void Clear() {
 
        _value = "";
    };
 
    void Append(StringElement element) {
 
        _value.append(element);
    };
 
    operator std::string() const {
 
        return _value;
    };
 
    StringBuilder &operator<<(StringElement se) {
     
        Append(se); return *this;
    };
 
    operator const char *() const {
 
        return _value.c_str();
    };
};
 
#endif _STRING_BUILDER_H
C/C++ code
 
?
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
#ifndef _STRING_ELEMENT_H
#define _STRING_ELEMENT_H
 
#include <string>
#include <sstream>
 
class StringElement {
 
private:
    template<typename T> std::string ToString(T &val) {
 
        std::stringstream ss;
        ss << val;
        std::string retVal;
        ss >> retVal;
 
        return retVal;
    };
 
    std::string _value;
 
public:
    StringElement(int i) : _value(ToString<int>(i)) {
    };
     
    StringElement(double d) : _value(ToString<double>(d)) {
    };
     
    StringElement(char c) : _value(ToString<char>(c)) {
    };
     
    StringElement(char *cp) : _value(cp) {
    };
 
    StringElement(const std::string s) : _value(s) {
    };
     
    StringElement(long l) : _value(ToString<long>(l)) {
    };
     
    StringElement(float f) : _value(ToString<float>(f)) {
    };
     
    StringElement(short s) : _value(ToString<short>(s)) {
    };
     
    StringElement(bool b) : _value(ToString<bool>(b)) {
    };
 
    operator std::string() const {
 
        return _value;
    };
};
 
#endif _STRING_ELEMENT_H
C/C++ code
 
?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
#include "StringBuilder.h"
#include <fstream>
 
#define SUCCESS 1
#define FAILURE 0
 
int log(std::string message) {
 
    std::ofstream logfile("log.txt", std::ios::out | std::ios::app);
    logfile << message << std::endl;
 
    return SUCCESS;
};
 
int main() {
     
    log(SB << "The number is " << 1);
    int x = 1, y = 2;
    printf(SB << "x=" << x << " and y=" << y); 
};
 
posted @ 2017-02-27 19:28  sky20080101  阅读(87)  评论(0)    收藏  举报