1-21
这个题真看不懂, 写的画蛇添足。不过if-else,用的很合理。
#include <stdio.h>
#define TABINC 8
main()
{
int c, nb, nt, pos;
nb = 0;
nt = 0;
for(pos=1; (c=getchar()) != EOF; pos++)//输入字符
if(c==' ')//为空格时
{
if(pos%TABINC != 0)//空格不够8个时,
nb++;
else//够8个时,
{
nt++;//统计制表符,
nb = 0;//空格数清理
}
}
else//非空格时,
{
for(; nt>0; nt--)//打印制表符,
{
putchar('\t');
}
if(c == '\t')//当输入的是制表符时,删掉空格,!!!!不理解,它怎么保证单词之间间距,
nb = 0;
else//不是制表符,则打印空格,
for(; nb>0; nb--)
putchar(' ');
putchar(c);//打印其他,
if(c=='\n')//起始新行,
pos = 0;
else if(c == '\t')
pos += (TABINC-(pos-1)%TABINC)-1;//这里也不明白,为什么要把pos弄成制表符的倍数。
}
}
假设输入“1 , , ,\t,1,”那它岂不是两个1的间距缩短了吗?
1-22
这个代码写的很优美,拆分的合理。
#include <stdio.h>
#define MAXCOL 10
#define TABINC 8
char line[MAXCOL];
int exptab(int pos);
int findblnk(int pos);
int newpos(int pos);
void printl(int pos);
main()
{
int c, pos;
pos = 0;
while ((c=getchar()) != EOF) {
line[pos] = c;
if(c == '\t')
pos = exptab(pos);
else if(c == '\n')
{
printl(pos);
pos = 0;
}
else if (++pos >= MAXCOL) {
pos = findblnk(pos);
printl(pos);
pos = newpos(pos);
}
}
}
void printl(int pos)
{
int i = 0;
for(i=0; i<pos; i++)
putchar(line[i]);
if(pos>0)
putchar('\n');
}
int exptab(int pos)
{
line[pos] = ' ';
for(pos++; pos<MAXCOL && pos%TABINC != 0; pos++)
line[pos] = ' ';
if (pos < MAXCOL)
return pos;
else {
printl(pos);
return 0;
}
}
int findblnk(int pos)
{
while(pos>0 && line[pos]!=' ')
pos--;
if(pos==0)
return MAXCOL;
else {
return pos++;
}
}
int newpos(int pos)
{
int i, j;
if(pos<=0 || pos >= MAXCOL)
return 0;
else {
i = 0;
for(j=pos; j<MAXCOL; j++)
{
line[i] = line[j];
i++
}
return i;
}
}
不超过的直接打印,截断打印,移到首列,输入判断。