預處理指令與格式化 I/O 是 C 語言程式的骨架。本文系統整理宏定義、條件編譯、檔案包含、printf/scanf 格式字串、getchar 字元輸入等核心知識,附帶實戰範例與最佳實踐。
// 宏定義
#define PI 3.14159
#define SQUARE(x) ((x)*(x)) // 帶參數宏,括號防優先級錯誤
#define LOG(msg) printf("%s\n", msg) // 字串化
#define STR(x) #x // 字串化運算子
#define CAT(a,b) a##b // 連接運算子
// 條件編譯
#ifdef DEBUG
#define DBG(fmt, ...) printf(fmt, __VA_ARGS__)
#else
#define DBG(fmt, ...)
#endif
#ifndef CONFIG_H
#define CONFIG_H
// 防重複包含
#endif
// #undef 取消宏
#undef PI
// 檔案包含
#include "myheader.h" // 先找當前目錄,再找 include 路徑
#include <stdio.h> // 只找系統 include 路徑
int a = 88; float b = 3.14159; char *c = "webabcd";
printf("%d, %.2f, %.7s\n", a, b, c); // 88, 3.14, webabcd
printf("%o, %#o\n", a, a); // 130, 0130 (八進位)
printf("%x, %#x, %#X\n", a, a, a); // 58, 0x58, 0X58 (十六進位)
printf("%10.2f\n", b); // " 3.14" (寬度10,右對齊)
printf("%-10.2f\n", b); // "3.14 " (左對齊)
int a; float b; char c[100];
scanf("%d%f%2s", &a, &b, c); // 空白分隔,%2s 只讀2字元
scanf("a=%d, b=%f, c=%s", &a, &b, c); // 精確匹配格式字串
// 返回值:成功賦值的參數個數,EOF 表示失敗
int ch;
while ((ch = getchar()) != '\n' && ch != EOF) {
putchar(ch); // 回聲
}
// getchar 從 stdin 緩衝區逐字元讀取,遇換行返回
// getch/getche 非標準 (conio.h),Linux 不支援
#include <stdio.h>
#define MAX_LEN 100
#define READ_INT(p) scanf("%d", p)
int main() {
int n;
printf("輸入整數:");
READ_INT(&n);
printf("你輸入了:%d\n", n);
return 0;
}
printf 格式字串與參數嚴格匹配,啟用編譯器警告 -Wformatscanf 必須傳址 &var,寬度限制防溢位 %99sscanf 與 getchar (殘留換行符問題),統一用 fgets + sscanf扎實掌握預處理與 I/O,能寫出可配置、健壯、可移植的 C 程式碼。