您的位置:首页 > 其它

练习1-22 编写一个程序,把较长的输入行折成短一些的两行或者多行,折行的位置在输入行的第N列之前的最后一个非空格之后。要保持程序能够智能地处理输入行很长以及在制定的列前没有空格或者制表符时的情况。

2013-10-25 23:11 881 查看
题目理解:自定义n为行的极限长度,输入行超过n列则进行折行操作,并且需要每列的开头不能是空格和制表符

例如n = 3 输入 aaaa 则输出 aaa

              a

在有空格和制表符的情况输入 aaa空格空格制表符制表符a

           输出 aaa

              a(不带空格和制表符)。

我的答案:

#include <stdio.h>
#define LINEN 2 /*设置折行位置字符*/

main()
{
int c, pos;
pos = 1;/*当前输入位置*/
while((c = getchar()) != EOF)
if(c == ' ' || c == '\t')
{
putchar('\b');
}else if (c == '\n')
{
putchar(c);
pos = 1;
}else
{
putchar(c);
++pos;
while(pos > LINEN){
putchar('\n');
putchar(c);
break;
}
}

return 0;

}


View Code
达不到题目要求.看答案

#include <stdio.h>
#define MAXCOL 3   /* maximum colum of input*/
#define TABINC 8    /* tab increment size*/

char line[MAXCOL]; /* input line*/

int exptab(int pos);
int findblnk(int pos);
int newpos(int pos);
void printl(int pos);
/*fold long input lines into two or more shorter lines*/

main()
{
int c, pos;

pos = 0; /*position is the line*/
while ((c = getchar()) != EOF)
{
line[pos] = c; /* store current character*/
if(c == '\t')      /* expand tab character */
pos = exptab(pos);
else if (c == '\n')
{
printl(pos); /*  print current input line */
pos = 0;
}else if (++ pos >= MAXCOL)
{
pos = findblnk(pos);
printl(pos);
pos = newpos(pos);
}

}

}

/*printl: print line until pos column8*/

void printl(int pos)
{
int i;
for(i = 0; i < pos; ++i)
putchar(line[i]);
if(pos > 0)         /*any chars printed?*/
putchar('\n');
}

/* exptab: expand tab into blanks */

int exptab(int pos)
{
line[pos] = ' ';        /*tab is at least one blank */
for(++pos; pos < MAXCOL && pos % TABINC != 0; ++pos)
line[pos] = ' ';
if(pos < MAXCOL)               /*room left incurrent line*/
return pos;
else                            /* current line is full*/
{
printl(pos);
return 0;                   /* reset current position*/
}
}

/* findblnk : find blank's position*/

int findblnk(int pos)
{
while (pos > 0 && line[pos] != ' ')
--pos;
if(pos == 0)                /*no blanks in the line ?*/
return MAXCOL;
else                            /*at least one blank*/
return pos+1;              /*position after the blank*/
}

/*newpos:  rearrange line with new position*/

int newpos(int pos)
{
int i, j;
if(pos <= 0 || pos >= MAXCOL)
return 0;           /*nothing to rearrange*/
else
{
i = 0;
for(j = pos ; j < MAXCOL; ++j)
{
line[i] = line[j];
++i;
}
return i;       /*new position in line*/
}
}


对题目要求还不够理解透彻

题目要求的“要保持程序能够智能地处理输入行很长以及在制定的列前没有空格或者制表符时的情况” 答案貌似也没能够去掉多余的空格和制表符.
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐