结构体:不同数据的集合。
struct 结构体名{
成员列表
};
例1:struct student{ //struct student 结构类型
int ID;
char name[20];
}
例2:
第一种:
#include <stdio.h>
#include<iostream>
#include <string.h>
#include<cstdio>
using namespace std;
struct student {
int ID;
string name;
int score;
};
int main() {
int ID = 10;
struct student stu;//定义一个结构体变量
stu.ID = 101;
stu.name = "Liming";
//printf("ID =%d\n,name=%s\n", stu.ID, stu.name);
printf("%s\n", stu.name.c_str());//此可以换成头文件为iostream,然后cout<<"ID="<<stu.name;因为pintf输出字符串是针对 //char*的,string不是c的内置函数
system("pause");
}
第二种
#include <stdio.h>
#include<iostream>
#include <string.h>
#include<cstdio>
using namespace std;
struct student {
int ID;
string name;
int score;
}stu;
int main() {
stu = {101,"Ling"};//定义一个结构体变量
struct student th;
printf("ID=%d\n name=%s\n",stu.ID, stu.name.c_str());
system("pause");
}
例3 结构体的嵌套
#include <stdio.h>
#include<iostream>
#include <string.h>
#include<cstdio>
using namespace std;
struct student {
int ID;
//string name;
string name;
int score;
struct teacher {
int age;
}th;
};
int main() {
int ID = 10;
struct student stu;//定义一个结构体变量
stu.ID = 101;
stu.name ="Liming";
struct student th;
stu.th.age = 18;
printf("%s\n", stu.name.c_str());
printf("teacher's age=%d\n", stu.th.age);
system("pause");
}
例4 语言中用关键字typedef可以为数据类型定义一个别名。
#include <stdio.h>
#include<iostream>
#include <string.h>
#include<cstdio>
using namespace std;
typedef struct student {
int ID;
string name;
int score;
}stu;//stu等价于struct student
int main() {
stu A= {101,"Ling"};//定义一个结构体变量
struct student th;
printf("ID=%d\nname=%s\n",A.ID, A.name.c_str());
system("pause");
}
例5 结构体指针//指针既可以指向数组,也可以指向结构体
(1)var.成员
(2)pointer->成员
#include <stdio.h>
#include<iostream>
#include <string.h>
#include<cstdio>
using namespace std;
typedef struct student {
int ID;
string name;
int score;
}stu;
int main() {
stu A= {101,"Ling"};//定义一个结构体变量
printf("ID=%d\nname=%s\n",A.ID, A.name.c_str());
stu* pb = &A;
pb->ID = 201;
printf("ID=%d\nname=%s\n", A.ID, A.name.c_str());
system("pause");
}
例6.结构体,定义成员数组
#include <stdio.h>
#include<iostream>
#include <string.h>
#include<cstdio>
using namespace std;
typedef struct student {
int ID;
string name;
int score;
}stu;
int main() {
stu A[10];
A[0]= {101,"Ling"};//定义一个结构体变量
printf("A[0]的ID=%d,name=%s\n",A[0].ID, A[0].name.c_str());
stu* pb = &A[0];
pb->ID = 201;
printf("A[0]的ID=%d,name=%s\n", A[0].ID, A[0].name.c_str());
A[1] = { 301,"Lily" };//定义一个结构体变量
printf("A[1]的ID=%d,name=%s\n", A[1].ID, A[1].name.c_str());
system("pause");
}