• C语言之struct-->(结构体数组)


    C语言的结构体是一种特殊的数据类型,或者称之为高级的数据类型,我们常说的int,long,float,double都属于基础类型,基础类型只能存储类型一致的数据。而结构体则能够存储不同的类型,它能够存储int ,char ,long 的复合类型。下面是一个我用结构体写的简单的实例,使用结构体先构造一个book类型的结构体,可以存储多个book类型的值,这个称为结构体数组,代码的第22行声明了一个结构数组,顾名思义,结构数组是指能够存放多个结构体类型的一种数组形式。

     1 /**
     2     该程序使用结构体构造了一个简单的书籍结构体
     3     主要是结构体数组的使用方法 
     4 */
     5 #include <stdio.h> 
     6 #define MAX_TITLE_SIZE 30
     7 #define MAX_AUTHOR_SIZE 40
     8 #define MAX_SIZE 2
     9 //构造一个BOOK结构体,用于存放title,author,price  
    10 struct book
    11 {
    12    char title[MAX_TITLE_SIZE];
    13    char author[MAX_AUTHOR_SIZE];
    14    float price;    
    15 };
    16 int main()
    17 {
    18     //设置一个计数器,用来计数输入的次数 
    19     int count=0;
    20     //设置另外一个计数器,用来遍历显示输入的book 
    21     int index=0;
    22     struct book lib[MAX_SIZE];
    23     printf("Set Book Title 
    ");
    24     //对相关的参量进行数据输入 
    25     while(count<MAX_SIZE&&
    26           printf("title is:")&&gets(lib[count].title)!=NULL && lib[count].title[0]!='
    ')
    27             {
    28                printf("SET Your AUthor : 	");
    29                gets(lib[count].author);
    30                printf("SET BOOKS price: 	");
    31                 scanf("%f",&lib[count].price);
    32                     count++;
    33                     //如果不为
    ,就继续下一次的数据输入 
    34                 while(getchar()!='
    ')
    35                 {
    36                     continue;
    37                 }
    38             
    39                 if(count<MAX_SIZE)
    40                 {
    41                     printf("Enter to next LINE to set title
    ");
    42                     
    43                 }
    44             }
    45        if(count>0)
    46         {
    47             printf("Here are book lists 
    ");
    48             //遍历结构体数组 
    49            for(index=0;index<count;index++)
    50                {
    51                 printf("The Title is %s And The Author is %s And price is %f 
    "
    52                             ,lib[index].title,lib[index].author,lib[index].price);           
    53                }    
    54         }
    55     return 0;
    56 } 

    以下是代码的运行结果

  • 相关阅读:
    关于字体单位em的问题
    键盘按钮keyCode大全
    右侧导航栏(动态添加数据到list)
    当前页面点击取到值
    前端写分页(用了自己同事写的插件)
    选择控件js插件和使用方法
    Form表单验证
    前端页面跳转并取到值
    App配置页面头部
    json字符串、json对象、数组之间的转换
  • 原文地址:https://www.cnblogs.com/zhengzuozhanglina/p/6012026.html
Copyright © 2020-2023  润新知