C 语言结构体输出207


在 C 语言中,结构体是一种复合数据类型,它允许将不同类型的数据组织为一个单元。输出结构体变量中的数据时,我们需要使用合适的语法和格式化选项。

直接访问成员

最直接的方法是直接访问结构体的成员:
```c
struct student {
int id;
char name[20];
float gpa;
};
int main() {
struct student s1 = {1, "John Doe", 3.5};
printf("ID: %d", );
printf("Name: %s", );
printf("GPA: %.2f", );
return 0;
}
```
输出结果:
```
ID: 1
Name: John Doe
GPA: 3.50
```

使用指针

也可以使用指针来访问结构体的成员:
```c
struct student {
int id;
char name[20];
float gpa;
};
int main() {
struct student s1 = {1, "John Doe", 3.5};
struct student *ptr = &s1;
printf("ID: %d", ptr->id);
printf("Name: %s", ptr->name);
printf("GPA: %.2f", ptr->gpa);
return 0;
}
```
输出结果与直接访问的方式相同。

使用宏

可以通过定义一个宏来简化结构体成员的访问:
```c
#define GET_MEMBER(member) ((*(member)).member)
int main() {
struct student s1 = {1, "John Doe", 3.5};
printf("ID: %d", GET_MEMBER(&s1).id);
printf("Name: %s", GET_MEMBER(&s1).name);
printf("GPA: %.2f", GET_MEMBER(&s1).gpa);
return 0;
}
```
输出结果与上述方式相同。

格式化输出

我们可以使用 printf() 函数的格式化字符串来指定输出格式:
```c
int main() {
struct student s1 = {1, "John Doe", 3.5};
printf("%-6s%-20s%6s", "ID", "Name", "GPA");
printf("%-6d%-20s%6.2f", , , );
return 0;
}
```
输出结果:
```
ID Name GPA
1 John Doe 3.50
```

自定义输出函数

也可以定义一个自定义的输出函数来格式化和输出结构体数据:
```c
#include
struct student {
int id;
char name[20];
float gpa;
};
void print_student(struct student *s) {
printf("ID: %d", s->id);
printf("Name: %s", s->name);
printf("GPA: %.2f", s->gpa);
}
int main() {
struct student s1 = {1, "John Doe", 3.5};
print_student(&s1);
return 0;
}
```
输出结果:
```
ID: 1
Name: John Doe
GPA: 3.50
```

2024-10-23


上一篇:C 语言输出结构体:深入指南

下一篇:C 语言函数——程序代码示例