存儲 10 本圖書信息 (書號、書名、放置地點),支持用戶輸入書號**或**部分書名,輸出對應放置地點。核心知識點:結構體、數組、字符串處理、輸入輸出、查找算法。
#define MAX_BOOKS 10
#define MAX_TITLE_LEN 50
#define MAX_LOC_LEN 30
typedef struct {
char id[20]; // 書號
char title[MAX_TITLE_LEN]; // 書名
char location[MAX_LOC_LEN]; // 放置地點
} Book;
Book library[MAX_BOOKS];
int book_count = 0;
fgets 讀取含空格書名,去除換行符。
void search_book(const char *query) {
int found = 0;
for (int i = 0; i < book_count; i++) {
// 精確匹配書號
if (strcmp(library[i].id, query) == 0) {
printf("書號: %s | 書名: %s | 地點: %s\n", library[i].id, library[i].title, library[i].location);
found = 1;
continue;
}
// 模糊匹配書名 (strstr 子串查找)
if (strstr(library[i].title, query) != NULL) {
printf("書號: %s | 書名: %s | 地點: %s\n", library[i].id, library[i].title, library[i].location);
found = 1;
}
}
if (!found) printf("未找到匹配的圖書。\n");
}
#include
#include
#include
// ... 結構體定義 ...
void safe_gets(char *buf, int len) {
fgets(buf, len, stdin);
buf[strcspn(buf, "\n")] = '\0';
}
int main() {
// 初始化示例數據 (可改為手動輸入)
strcpy(library[0].id, "ISBN001"); strcpy(library[0].title, "C Primer Plus"); strcpy(library[0].location, "A架-1層");
// ... 填充其餘 9 本 ...
book_count = 10;
char input[100];
while (1) {
printf("\n1. 查詢 2. 退出\n選擇: ");
safe_gets(input, sizeof(input));
if (input[0] == '2') break;
if (input[0] == '1') {
printf("輸入書號或書名關鍵字: ");
safe_gets(input, sizeof(input));
search_book(input);
}
}
return 0;
}
從「結構體數組 + 線性查找」起步,掌握數據建模、字符串處理、交互循環三大基礎能力,是 C 語言從語法走向工程的關鍵一步。