您的位置:首页 > 其它

Selected solutions to exercise of "The C Programming Language" 2e (Part 6)

2006-02-19 23:16 639 查看

Exercise 1-22

Write a program to "fold" long input lines into two or more shorter lines after the last non-blank character that occurs before the n -th column of input. Make sure your program does something intelligent with very long lines, and if there are no blanks or tabs before the specified column.

/*
KnR 1-22
----------
Write a program that wraps very long lines of input
into two or more shorter lines.
*/

#include <stdio.h>

#define MAXLINE 1000 /* max input line size */
#define FOLDLENGTH 80

/* current input line */
char line[MAXLINE];

/* taken from the KnR book. */
int getline(void);
/* print the line, from index of start to end */
void print(int start, int end);
/* find the last space in line from index of start to end */
int find_last_space(int start, int end);

int main()
{
int len;

while (( len = getline()) > 0 )
{
print(0, len);
}
return 0;
}

/* getline: specialized version */
int getline(void)
{
int c, i;
extern char line[];

for (i = 0;
i < MAXLINE-1 && (c = getchar()) != EOF && c != '/n'; ++i)
line[i] = c;

if(c == '/n')
{
line[i] = c;
++i;
}
line[i] = '/0';
return i;
}

int find_last_space(int start, int end) {
int place = -1;
int i = start;
int len = 1; /* the length from start to current postion */

for (; i < end && len <= FOLDLENGTH; i++, len++) {
if (line[i] == ' ') {
place = i;
}
}
return place;
}

void print(int start, int end) {
int len = end - start;
int place = -1;
int i = 0;
if (len <= FOLDLENGTH) {
for (i = start; i < end; i++)
printf ( "%c", line[i]);
return;
}
else {
/* find a proper space */
if ((place = find_last_space(start, end)) != -1 ) {
print(start, place + 1);
printf("/n");
print(place + 1, end);
} else {
print(start, start + FOLDLENGTH);
printf("/n");
print(start + FOLDLENGTH, end);
}
}
}

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐