實現一個基於行的簡單編輯器,支持:
#:退格刪除前一字符(棧彈出)@:刪除整行(清空棧)#define STACK_INIT_SIZE 100
#define STACKINCREMENT 10
struct SqStack {
char *base;
char *top;
int stacksize;
};
void InitStack(SqStack &S) {
S.base = (char*)malloc(STACK_INIT_SIZE * sizeof(char));
if (!S.base) exit(1);
S.top = S.base;
S.stacksize = STACK_INIT_SIZE;
}
void Push(SqStack &S, char e) {
if (S.top - S.base >= S.stacksize) {
S.base = (char*)realloc(S.base, (S.stacksize+STACKINCREMENT)*sizeof(char));
if (!S.base) exit(1);
S.top = S.base + S.stacksize;
S.stacksize += STACKINCREMENT;
}
*S.top++ = e;
}
char Pop(SqStack &S, char &e) {
if (S.top == S.base) return 0;
e = *--S.top;
return e;
}
void ClearStack(SqStack &S) { S.top = S.base; }
bool StackEmpty(SqStack &S) { return S.top == S.base; }
void DestroyStack(SqStack &S) { free(S.base); S.top = S.base; }
void main() {
char ch, e;
SqStack S, D; // S: 當前行棧, D: 輸出翻轉棧
InitStack(S); InitStack(D);
ch = getchar();
while (ch != EOF) {
while (ch != EOF && ch != '\n') {
switch (ch) {
case '#': Pop(S, e); break; // 退格
case '@': ClearStack(S); break; // 刪除整行
default: Push(S, ch); break; // 普通字符入棧
}
ch = getchar();
}
// 行結束,將 S 逆序轉入 D 再輸出
while (!StackEmpty(S)) { Pop(S, e); Push(D, e); }
while (!StackEmpty(D)) { Pop(D, e); printf("%c", e); }
ClearStack(S);
if (ch != EOF) ch = getchar();
}
DestroyStack(S);
}
getchar()),無需緩衝整行。