1 #include <stdio.h>
2 #define MAXCOL 3 /* maximum colum of input*/
3 #define TABINC 8 /* tab increment size*/
4
5 char line[MAXCOL]; /* input line*/
6
7 int exptab(int pos);
8 int findblnk(int pos);
9 int newpos(int pos);
10 void printl(int pos);
11 /*fold long input lines into two or more shorter lines*/
12
13 main()
14 {
15 int c, pos;
16
17 pos = 0; /*position is the line*/
18 while ((c = getchar()) != EOF)
19 {
20 line[pos] = c; /* store current character*/
21 if(c == '\t') /* expand tab character */
22 pos = exptab(pos);
23 else if (c == '\n')
24 {
25 printl(pos); /* print current input line */
26 pos = 0;
27 }
28 else if (++ pos >= MAXCOL)
29 {
30 pos = findblnk(pos);
31 printl(pos);
32 pos = newpos(pos);
33 }
34
35 }
36 }
37
38 /*printl: print line until pos column8*/
39
40 void printl(int pos)
41 {
42 int i;
43 for(i = 0; i < pos; ++i)
44 putchar(line[i]);
45 if(pos > 0) /*any chars printed?*/
46 putchar('\n');
47 }
48
49
50 /* exptab: expand tab into blanks */
51
52 int exptab(int pos)
53 {
54 line[pos] = ' '; /*tab is at least one blank */
55 for(++pos; pos < MAXCOL && pos % TABINC != 0; ++pos)
56 line[pos] = ' ';
57 if(pos < MAXCOL) /*room left incurrent line*/
58 return pos;
59 else /* current line is full*/
60 {
61 printl(pos);
62 return 0; /* reset current position*/
63 }
64 }
65
66
67 /* findblnk : find blank's position*/
68
69 int findblnk(int pos)
70 {
71 while (pos > 0 && line[pos] != ' ')
72 --pos;
73 if(pos == 0) /*no blanks in the line ?*/
74 return MAXCOL;
75 else /*at least one blank*/
76 return pos+1; /*position after the blank*/
77 }
78
79
80 /*newpos: rearrange line with new position*/
81
82 int newpos(int pos)
83 {
84 int i, j;
85 if(pos <= 0 || pos >= MAXCOL)
86 return 0; /*nothing to rearrange*/
87 else
88 {
89 i = 0;
90 for(j = pos ; j < MAXCOL; ++j)
91 {
92 line[i] = line[j];
93 ++i;
94 }
95 return i; /*new position in line*/
96 }
97 }
1.对题意“折行的位置在输入行的第n列之前的最后一个非空格符之后”的理解:比如每隔10个字符折成一行,
如果这10个字符中间没有空格,则输出;如果有一个空格,则输出位置0开始的字符到本空格处之间的所有字符;
如果有若干个空格,则输出位置0到最后一个空格处之间所有字符。
例如:输入:abc/tdefg
输出:abc
def
g
输入:abc def ghk
输出:abc
de
f
ghk
2. 对从输入缓冲区中读取的每个字符c,依据c == '/t',c == '/n',++pos >= MAXCOL分成三类处理。
缺陷:如同分析1中的第一种输入输出情况,第二行输出为空行;第二种输入输出情况,第二行输出时,头部输出了空格,可以将输出行头部的空格去掉,将会更加严谨。
浙公网安备 33010602011771号