您的位置:首页 > 其它

读《The C Programming Language》(3)

2006-02-08 21:05 316 查看
做了第一章的几个练习题。

Exercise 1-20. Write a program detab that replaces tabs in the input with the proper number of blanks to space to the next tab stop. Assume a fixed set of tab stops, say every n columns. Should n be a variable or a symbolic parameter?

#include <stdio.h>

#define TABWIDTH 8

main()
{
int c, i;
int nchar = 0; /* counts the char number before tab */

while ((c = getchar()) != EOF)
{
if (c == '/t')
{
for (i = 0; i < TABWIDTH - nchar % TABWIDTH; i++)
putchar(' ');
nchar = 0;
}
else
{
putchar(c);

if (c == '/n')
nchar = 0;
else
nchar++;
}
}
}

Exercise 1-21. Write a program entab that replaces strings of blanks by the minimum number of tabs and blanks to achieve the same spacing. Use the same tab stops as for detab. When either a tab or a single blank would suffice to reach a tab stop, which should be given preference?

#include <stdio.h>

#define TABINC 8

main()
{
int pos, /* position indicator */
counter, /* counts the blanks in blank string */
ntab, /* tabs to be replaced with */
nblank, /* the rest blanks to fill */
c; /* receive the input char */

pos = counter = 0;

while ((c = getchar()) != EOF)
{
if (c == ' ')
{
pos++;
counter++;
}
else
{
if (counter > 0) /* replace blanks here */
{
ntab = pos/TABINC - (pos-counter)/TABINC;
if (ntab == 0)
nblank = counter;
else
nblank = pos % TABINC;

while (ntab > 0)
{
putchar('/t');
ntab--;
}
while (nblank > 0)
{
putchar(' ');
nblank--;
}
}

if (c == '/t')
pos += TABINC - pos % TABINC;
else if (c == '/n')
pos = 0;
else
pos++;

counter = 0;
putchar(c);
}
}
}

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.

#include <stdio.h>

#define SW 80 /* screen width */
#define COL 40 /* column for folding line */

main()
{
int c, pos, i;
char input[SW];

pos = 0;

while ((c = getchar()) != EOF)
{
if (COL >= SW)
{
putchar(c);
continue;
}

input[pos] = c;
if (c == '/n')
{
input[++pos] = '/0';
printf("%s", input);
pos = 0;
}
else if (pos == COL) /* exceed specified column */
{
while (pos >= 0)
{
if (input[pos] == ' ' || input[pos] == '/t')
break;
pos--;
}
if (pos == -1 || pos == COL)
{
input[COL] = '/n';
input[COL+1] = '/0';
printf("%s", input);

if (pos == -1) /* no blank or tab */
{
pos = 1;
input[pos] = c;
}
else /* a blank or tab is at the end */
pos = 0;
}
else /* wrap word here */
{
for (i = 0; i < pos; i++)
putchar(input[i]);
putchar('/n');

pos++;
for (i = 0; pos <= COL; i++, pos++)
input[i] = input[pos];
pos = i;
}
}
else
pos++;
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: