老師要求使用 < text.txt 重定向標準輸入 (stdin),程序無需顯式打開文件,直接用 scanf 讀取即可。
// 編譯
gcc program.c -o program
// 運行 (Windows/Linux/macOS 通用)
program < text.txt
Shell 將 text.txt 內容作為標準輸入流傳給程序,scanf 從 stdin 讀取,效果等同於鍵盤輸入。
文件內容示例:
3 12867 1.0 2.0 1.0 5.0 4.0 5.05
15643 1.0 2.0 4.0 5.0 7.8 3.5 5.0 0.4 1.0 0.44
18674 1.0 0.4 0.4 0.4 0.4 3.6 1.0 3.60
#include
int main() {
int npoints, id;
double x[6]; // 6 個浮點數
// 讀取第一行:npoints id x[0]...x[5]
if (scanf("%d %d", &npoints, &id) != 2) return 1;
for (int i = 0; i < 6; i++) {
if (scanf("%lf", &x[i]) != 1) return 1;
}
printf("npoints=%d, id=%d\n", npoints, id);
for (int i = 0; i < 6; i++)
printf("x[%d]=%.2f ", i, x[i]);
return 0;
}
while (scanf("%d %d", &npoints, &id) == 2) {
for (int i = 0; i < npoints * 2; i++) { // 假設每點 2 個坐標
double val;
scanf("%lf", &val);
// 處理 val
}
// 處理完一行數據
}
| 方式 | 優點 | 缺點 |
|---|---|---|
| stdin 重定向 | 代碼簡潔,無文件操作錯誤,便於管道組合 | 無法隨機訪問,難以處理多文件 |
| fopen/fscanf | 隨機訪問,多文件處理,錯誤控制細緻 | 代碼較繁瑣,需手動管理文件指針 |
適用場景:競賽編程、批量數據處理、管道流式計算。