制表符和空白符替换有疑惑
练习5-11 修改程序entab和detab,使他们接受一组作为参数的制表符停止位。如果启动程序时不带参数,则使用默认的制表符停止位设置疑问部分:代码绿色注释部分
程序代码:Detab.cpp:#include<stdio.h> [color=#0000FF]#defineMAXLINE 100 #define TABINC 8 #define YES 1 #define NO 0 void settab(int argc, char *arg[], char *tab); void detab(char *tab); int tabpos(int pos, char *tab); int main(int argc, char *argv[]) { char tab[MAXLINE + 1]; settab(argc, argv, tab); detab(tab); return 0; } void detab(char *tab) { int c, pos = 1; while((c = getchar()) != EOF) if (c == '\t') { do putchar(' '); while (tabpos(pos++, tab) != YES); } else if (c == '\n') { putchar(c); pos = 1; } else { putchar(c); ++pos; } }
Settab.cpp:
程序代码:#include<stdlib.h>
#define MAXLINE 100
#define TABINC 8
#define YES 1
#define NO 0
void settab(int argc, char *argv[], char *tab)
{
int i, pos;
if (argc <= 1) // 这里if语句是没输入参数时默认制表,通过返回YES来确定pos现在的位置
for (i = 1; i <= MAXLINE; i++)
if (i % TABINC == 0)
tab[i] = YES;
else
tab[i] = NO;
else // 不明白就是else语句中他是怎么来确认制表长度的,没看懂
{
for (i = 1; i <= MAXLINE; i++)
tab[i] = NO;
while (--argc > 0)
pos = atoi(*++argv);
if (pos > 0 && pos <= MAXLINE)
tab[pos] = YES;
}
}Tabpos.cpp:
程序代码:#define MAXLINE 100
#define YES 1
int tabpos(int pos, char *tab)
{
if (pos > MAXLINE)
return YES;
else
return tab[pos];
}[此贴子已经被作者于2017-5-15 18:18编辑过]




