手抄代碼1-21

1-21

這個題真看不懂, 寫的多此一舉。不過if-else,用的很合理。code

#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的間距縮短了嗎?get

1-22

這個代碼寫的很優美,拆分的合理。io

#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;
     }
}

不超過的直接打印,截斷打印,移到首列,輸入判斷。class

相關文章
相關標籤/搜索