用 C模拟面向对象思想

自编题:任意给定两个字符串,比如"The UNIX.... " 和 "The only ...." 如何如下显示? 用纯C实现。

 

 1 #include <stdio.h>
 2 #include <string.h>
 3 #define L 23
 4 #define C 80
 5 typedef struct{
 6     int l, c;  // lines, cols
 7 } pos_t;
 8 
 9 typedef struct {
10     char *str;
11     pos_t pos;
12     int w, h; // the width and height of a recttangle
13     void(*set)(void *);  // the way of display
14 } str_obj;
15 
16 char buf[L][C];
17 
18 void init(void)
19 {
20     memset(buf, ' ', L*C);
21 }
22 void display(void)
23 {
24   buf[L][C] = 0;
25   printf("%s", buf);
26 }
27 void set_pixel(int x, int y, char c)
28 {
29     if(y>0&&y<=L && x>0&&x<=C)
30         buf[y-1][x-1] = c;
31 }
32 
33 static void hor_line(int c, int l, int length)
34 {
35     set_pixel(c, l, '+');
36     int i;
37     for(i=c+1; i<length+c-1; i++)
38         set_pixel(i, l, '-');
39     set_pixel(i,l, '+');
40 }
41 
42 static void ver_line(int c, int l, int length)
43 {
44     set_pixel(c, l, '+');
45     int i;
46     for(i=l+1; i<length+l-1; i++)
47         set_pixel(c, i, '|');
48     set_pixel(c, i, '+');
49 }
50 
51 void print(void *obj) 
52 {
53     str_obj *p = obj;
54     char *str = p->str;
55     int x = p->pos.c, y = p->pos.l;
56     int w = p->w, h = p->h;
57     hor_line(x-2, y-1, w+4);
58     ver_line(x-2, y-1, h+2);
59     hor_line(x-2, y+h, w+4);
60     ver_line(x+w+1, y-1, h+2);
61     int i,j;
62     int len = strlen(str), count = 0;
63     for(i=0; i<h; i++){ 
64         for(j=0; j<w; j++){
65                 if(count < len ){
66                     set_pixel(j+x,y+i, str[count++]);
67                 }
68         }
69     }
70 }
71 
72 int main(int argc, char **argv)
73 {
74 
75     init();
76     
77     str_obj xstr = {
78        "The UNIX operating system provides its services through "
79        "a set of system calls, which are in effect functions wit"
80        "hin the operating system that may be called by user prog"
81        "rams. This chapter describes how to use some of the most"
82        " important system calls from C programs.",
83         {2,5}, 15,20, print
84     };
85  
86         xstr.set(&xstr);
87         xstr.pos.c += xstr.w+3;
88         xstr.set(&xstr);
89 
90     str_obj ystr = {
91         "The only way to learn a new programming language is by "
92         "writing programs in it.",
93         {5, 50}, 20, 5, print
94     };
95         ystr.set(&ystr);
96         display();
97     return 0;
98 }

 

转载于:https://www.cnblogs.com/mathzzz/archive/2012/07/15/2592750.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值