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 TAB 8
void entab(int space);
int main()
{
int c, i;
i = 0;
while ((c = getchar()) != EOF)
{
if (c == )
++i;
else if (c == )
i = i + TAB;
else
{
entab(i);
i = 0;
putchar(c);
}
}
return 0;
}
void entab(int space)
{
int i;
for (i = 1; space >= TAB; ++i)
if (i == TAB)
{
putchar( );
i = 0;
space = space - TAB;
}
for (i = 0; i < space; ++i)
putchar( );
}
但是,当我提供“3个空白空间+5个空白空间+j”投入时,我获得的产出比投入更长:
图一第一行是投入,第二行是产出 最新情况: 根据其中一项评论和一项答复重新拟订该守则: but now the problem is that it s always one characters less than the input:
#include <stdio.h>
#define TAB 8
void entab(int space);
int main()
{
int c, i, l;
i = l = 0;
while ((c = getchar()) != EOF)
{
++l;
if (c == )
++i;
else if (c == )
i = i + TAB - (l%8);
else
{
entab(i);
i = 0;
putchar(c);
}
if (c ==
)
l = 0;
}
return 0;
}
void entab(int space)
{
int i;
for (i = 0; space >= TAB; ++i)
if (i == TAB)
{
putchar( );
i = -1;
space = space - TAB;
}
for (i = 0; i < space; ++i)
putchar( );
}