zoukankan      html  css  js  c++  java
  • Screen类:primer12.14

     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 << '
    ';
    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 }
  • 相关阅读:
    spacy 语言包离线安装
    linux 进程通信
    UNIX网络编程5 POSIX 消息队列
    UNIX网络编程 12 15共享内存区
    高级UNIX环境编程13 守护进程
    高级UNIX环境编程11 线程
    高级UNIX环境编程10 信号
    高级UNIX环境编程7 进程
    高级UNIX环境编程5 标准IO库
    高级UNIX环境编程4 文件和目录
  • 原文地址:https://www.cnblogs.com/jiangyoumiemie/p/3145064.html
Copyright © 2011-2022 走看看