#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define MAX_ROWS 100
#define MAX_NAME 50
#define MAX_EMAIL 50
typedef struct {
int id;
char name[MAX_NAME];
char email[MAX_EMAIL];
} Row;
typedef struct {
int size;
Row rows[MAX_ROWS];
} Table;
void init_table(Table *table) {
table->size = 0;
}
void insert_row(Table *table, int id, const char *name, const char *email) {
if (table->size < MAX_ROWS) {
Row *row = &table->rows[table->size];
row->id = id;
strncpy(row->name, name, MAX_NAME);
strncpy(row->email, email, MAX_EMAIL);
table->size++;
} else {
printf("Error: Table is full\n");
}
}
void print_table(Table *table) {
printf("ID\tName\tEmail\n");
for (int i = 0; i < table->size; i++) {
printf("%d\t%s\t%s\n", table->rows[i].id, table->rows[i].name, table->rows[i].email);
}
}
int main() {
Table table;
init_table(&table);
insert_row(&table, 1, "Alice", "alice@example.com");
insert_row(&table, 2, "Bob", "bob@example.com");
print_table(&table);
return 0;
}
-
头文件引用:
#include <stdio.h>#include <stdlib.h>#include <string.h>
引用了三个标准C语言库头文件,分别是标准输入输出库(stdio.h)、标准库(stdlib.h)和字符串处理库(string.h)。
-
宏定义:
#define MAX_ROWS 100 #define MAX_NAME 50 #define MAX_EMAIL 50
定义了三个常量,分别表示表格的最大行数、姓名的最大长度和电子邮件地址的最大长度。
-
数据结构定义:
typedef struct { int id; char name[MAX_NAME]; char email[MAX_EMAIL]; } Row
定义了一个表格行的结构体(Row),包含成员id、name和email。
typedef struct { int size; Row rows[MAX_ROWS]; } Table;
定义了一个表格的结构体(Table),包含成员size和一个表格行数组rows。
-
初始化表格函数:
void init_table(Table *table) { table->size = 0; }
该函数用于初始化表格,将表格的大小(size)设置为0。
-
插入行函数:
void insert_row(Table *table, int id, const char *name, const char *email) { if (table->size < MAX_ROWS) { Row *row = &table->rows[table->size]; row->id = id; strncpy(row->name, name, MAX_NAME); strncpy(row->email, email, MAX_EMAIL); table->size++; } else { printf("Error: Table is full\n"); } }
该函数用于向表格中插入新的行,如果表格未满,将在表格的下一个位置插入新行,否则输出错误信息。
-
打印表格函数:
void print_table(Table *table) { printf("ID\tName\tEmail\n"); for (int i = 0; i < table->size; i++) { printf("%d\t%s\t%s\n", table->rows[i].id, table->rows[i].name, table->rows[i].email); } }
该函数用于打印整个表格的内容,按照格式输出表头和每一行的信息。
-
主函数:
int main() { Table table; init_table(&table); insert_row(&table, 1, "Alice", "alice@example.com"); insert_row(&table, 2, "Bob", "bob@example.com"); print_table(&table); return 0; }
主函数创建一个Table类型的表格,并初始化。然后,通过insert_row函数向表格中插入两行数据,最后使用print_table函数打印整个表格的内容。