/* C程序設計語言 練習1-19: 編寫程序detab,將輸入中的製表符換成適當數據的空格,使空格充滿到下一個製表符終止位的地方。假設製表符終止位的位置是固定的,比如每個n列就會出現一個製表符終止位。n應該作爲變量還是符號常量呢? */
#include <stdio.h>
#define TABNUM 8
void detab(char text[]);
int main() {
char text[1000];
detab(text);
printf("%s\n", text);
return 0;
}
void detab(char text[]) {
char c;
int index = 0; /* 字符串索引 */
int pos = 1; /* 製表符終止位後或當前行的第pos個字符 */
int space_number; /* 空格的數量 */
while ((c = getchar()) != EOF) {
if (c == '\t') {
space_number = TABNUM - (pos - 1) % TABNUM;
while (space_number > 0) {
text[index] = ' ';
++index;
++pos;
--space_number;
}
} else if (c == '\n') {
text[index] = c;
pos = 1;
++index;
} else {
text[index] = c;
++index;
++pos;
}
}
}