練習(xí) 1 - 20 編寫程序 detab作谭,將輸入中的制表符替換成適當(dāng)數(shù)目的空格稽物,使空格充滿到下一個(gè)制表符終止的地方。假設(shè)制表符終止位的位置是固定的折欠,比如每隔 n 列就會(huì)出現(xiàn)一個(gè)制表符終止位贝或。n 應(yīng)該作為變量還是符號(hào)常量?
個(gè)人關(guān)于制表符及制表終止位的理解的一個(gè)不是很精確的描述:行按照一定的空格為間隔進(jìn)行劃分锐秦,制表符就相當(dāng)于光標(biāo)在一行中從當(dāng)前所在單位間隔跳到下一個(gè)單位間隔的起始位置咪奖。這個(gè)間隔的寬度為你在空行的行首按下 TAB 鍵是光標(biāo)移動(dòng)的列數(shù),不同的系統(tǒng)和軟件有所差異酱床。
本程序運(yùn)行平臺(tái)的 TAB 對(duì)應(yīng)的寬度為 8 列羊赵。因此制表符所占據(jù)的空格位置為
8 - (當(dāng)前行已打印的字符數(shù) % 8)
detab 的實(shí)現(xiàn)如下:
void detab(char line[]) {
int cnt = 1;
int idx = 0;
int space = 0;
while (line[idx] != '\0') {
if (line[idx] == '\t') {
space = TAB - cnt % TAB;
while (space >= 0) {
putchar(' ');
--space;
}
++idx;
}
putchar(line[idx++]);
++cnt;
}
}
完整代碼清單如下:
/* ex20.c - detab */
#include <stdio.h>
#define LIMIT 1000
#define TAB 8
void display(char line[]) {
int i = 0;
while (line[i] != '\0') {
putchar(line[i]);
++i;
}
putchar('\n');
}
void detab(char line[]) {
int cnt = 1;
int idx = 0;
int space = 0;
while (line[idx] != '\0') {
if (line[idx] == '\t') {
space = TAB - cnt % TAB;
while (space >= 0) {
putchar(' ');
--space;
}
++idx;
}
putchar(line[idx++]);
++cnt;
}
}
int getLine(char line[], int limit) {
int i = 0;
int c;
if ((c = getchar()) == EOF) {
return -1;
}
do {
line[i] = c;
++i;
} while ((c = getchar()) != '\n');
line[i] = '\0';
return (i + 1);
}
int main() {
char line[LIMIT];
while (getLine(line, LIMIT) > 0) {
detab(line);
putchar('\n');
}
return 0;
}
編譯運(yùn)行結(jié)果如下:
$ ./ex20.out
1234567890
1234567890
12 12
12 12
123456 123456
123456 123456
1234567812345678
1234567812345678
12345678 12345678
12345678 12345678
123
123
$