1 #include<iostream>
2 #include<string>
3
4 class Screen
5 {
6 public:
7 typedef std::string::size_type index;
8 Screen(const std::string &con, index hx, index wx);
9 char get() const
10 { return contents[cursor];}
11 inline char get(index hx, index wx) const;
12 inline index get_cursor() const;
13
14 Screen& move(index r, index c);
15 Screen& set(char ch);
16 const Screen& display(std::ostream &os) const;
17 Screen& display(std::ostream &os);
18
19 private:
20 std::string contents;
21 index cursor;
22 index height, width;
23 void Screen::do_display(std::ostream &os) const;
24 };
25
26 Screen::Screen(const std::string &con, index hx, index wx):
27 contents(con),height(hx),width(wx),cursor(0)
28 {
29 if(contents.size() > height * width)
30 height = contents.size()/width + 1;
31 else contents.replace(con.size(), height*width - con.size(), 1, ' ');
32 }
33
34 char Screen::get(index hx, index wx) const
35 {
36 return contents[wx + hx*width];
37 }
38
39 Screen::index Screen::get_cursor() const
40 {
41 return cursor;
42 }
43
44 Screen& Screen::move(index r, index c)
45 {
46 if(r >= height || c >= width)
47 {
48 std::cerr << "invalid row or column" << std::endl;
49 throw EXIT_FAILURE;
50 }
51 cursor = r * width + c;
52 return *this;
53 }
54
55 Screen& Screen::set(char ch)
56 {
57 contents[cursor] = ch;
58 return *this;
59 }
60
61 const Screen& Screen::display(std::ostream &os) const
62 {
63 do_display(os);
64 return *this;
65 }
66
67 Screen& Screen::display(std::ostream &os)
68 {
69 do_display(os);
70 return *this;
71 }
72
73 void Screen::do_display(std::ostream &os) const
74 {
75 for(index i = 0; i < contents.size(); ++i)
76 {
77 os << contents[i];
78 if( (i+1) % width == 0 )
79 os << '\n';
80 }
81 }
82
83
84 int main()
85 {
86 std::string str = "Youth,beautiful youth,I love you!love";
87 Screen scr(str,1,5);
88 str = "kkkkkkkkkkkkkkkkkkkk"; // 这个时候str的改变不会改变Screen。
89 scr.move(1,2).set('Z').display(std::cout).set('Z');
90 // scr.move(1,2);
91 scr.display(std::cout);
92 return 0;
93 }