-
Notifications
You must be signed in to change notification settings - Fork 0
/
streambuf_array_reader.cpp
89 lines (69 loc) · 1.96 KB
/
streambuf_array_reader.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
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
#include <iostream>
#include <streambuf>
#include <vector>
#include <functional>
#include <cassert>
class array_reader_streambuf : public std::streambuf {
public:
array_reader_streambuf(const char* begin, const char* end);
explicit array_reader_streambuf(const char* str);
private:
int_type uflow() override;
int_type underflow() override;
int_type pbackfail(int_type ch) override;
std::streamsize showmanyc() override;
private:
const char* const begin_;
const char* const end_;
const char* current_;
};
array_reader_streambuf::array_reader_streambuf(const char* begin, const char* end) :
begin_(begin),
end_(end),
current_(begin_)
{
assert(std::less_equal<const char*>()(begin_, end_));
}
array_reader_streambuf::array_reader_streambuf(const char* str) :
begin_(str),
end_(begin_ + std::strlen(str)),
current_(begin_)
{
}
array_reader_streambuf::int_type array_reader_streambuf::underflow()
{
if (current_ == end_)
return traits_type::eof();
return traits_type::to_int_type(*current_);
}
array_reader_streambuf::int_type array_reader_streambuf::uflow()
{
if (current_ == end_)
return traits_type::eof();
return traits_type::to_int_type(*current_++);
}
array_reader_streambuf::int_type array_reader_streambuf::pbackfail(int_type ch)
{
if (current_ == begin_ || (ch != traits_type::eof() && ch != current_[-1]))
return traits_type::eof();
return traits_type::to_int_type(*--current_);
}
std::streamsize array_reader_streambuf::showmanyc()
{
assert(std::less_equal<const char*>()(current_, end_));
return end_ - current_;
}
int main()
{
const char* text = "Dies ist ein String.";
array_reader_streambuf arsb(text);
std::istream in(&arsb);
std::string s;
while (in >> s)
std::cout << "--> " << s << std::endl;
in.clear();
for (int i=0; i<3; ++i)
in.unget();
while (in >> s)
std::cout << "==> " << s << std::endl;
}