程式碼意圖讀取鍵盤輸入寫入 ed.txt,但檔案始終為空。關鍵錯誤在第 27 行:
while(ch = !EOF) // 錯誤:賦值運算,ch 被設為 0 (假),迴圈不進入
// 應為
while(ch != EOF) // 比較運算,ch 不等於 EOF 才繼續
#include <stdio.h>
#include <stdlib.h>
#define STACK_INIT_SIZE 100
#define STACK_INCREMENT 10
#define OK 1
#define ERROR 0
#define OVERFLOW -2
#define TRUE 1
#define FALSE 0
typedef char SElemType;
typedef int Status;
typedef struct {
SElemType *base;
SElemType *top;
int stacksize;
} SqStack;
Status InitStack(SqStack &S) { ... } // 略
Status Push(SqStack &S, SElemType e) { ... }
Status Pop(SqStack &S, SElemType &e) { ... }
void StackTraverse(SqStack S, void(*visit)(SElemType)) { ... }
FILE *fp;
void copy(SElemType c) { fputc(c, fp); }
void LineEdit() {
SqStack s;
char ch;
InitStack(s);
printf("請輸入,Ctrl+Z 結束:\n");
ch = getchar();
while (ch != EOF) { // 修正處
while (ch != EOF && ch != '\n') {
switch (ch) {
case '#': if (!StackEmpty(s)) Pop(s, ch); break;
case '@': ClearStack(s); break;
default: Push(s, ch);
}
ch = getchar();
}
StackTraverse(s, copy);
fputc('\n', fp);
ClearStack(s);
if (ch != EOF) ch = getchar();
}
DestroyStack(s);
}
int main() {
fp = fopen("ed.txt", "w");
if (fp) {
LineEdit();
fclose(fp);
} else {
printf("建立檔案失敗!\n");
}
return 0;
}
gets 已棄用且不安全,建議用 fgets。SqStack*) 避免複製大結構體。