第14章 结构体和其他数据形式
通讯录
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
struct inof
{
char name[200];
long long phone;
};
void main2( void)
{
struct inof inof1;
strcpy(inof1.name, "xiaofeng");
inof1.phone = 15624024417;
printf("%s %lld \n",inof1.name,inof1.phone);
}
void main(void )
{
struct inof *p;
p=(struct inof *)malloc(sizeof(struct inof));
strcpy((*p).name, "xiaofeng1");
(*p).phone = 15624024418;
printf("%s %lld \n", p->name,p->phone);
}
仅包含一本图书的 图书目录
#define use _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
#include <stdlib.h>
#define MAXTTL 41
#define MAXAUTL 31
struct book{
char title[MAXTTL];
char author [MAXAUTL];
float value;
};
void main()
{
struct book bo;
printf("please enter the book title\n");
gets(bo.title);
printf("Now enter the author \n");
gets(bo.author);
printf("Now enter the value \n");
scanf("%f",&bo.value);
printf("%s by %s %.2f \n " , bo.title,bo.author,bo.value);
system("pause");
}
包含多本书的 图书目录
#define use _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
#include <stdlib.h>
#define MAXTTL 41
#define MAXAUTL 31
#define MAXBKS 100
struct book{
char title[MAXTTL];
char author [MAXAUTL];
float value;
};
void main()
{
int count = 0;
int index;
struct book library[MAXBKS];
printf("please enter the book title\n");
while (count < MAXBKS && gets(library[count].title)!= NULL && library[count].title[0] != '\0' )
{
printf("Now enter the author \n");
gets(library[count].author);
printf("Now enter the value \n");
scanf("%f",&library[count++].value);
while (getchar ()!= '\n')
{
continue;
}
if (count < MAXBKS)
{
printf("please enter the book title\n");
}
}
if (count > 0)
{
printf("here is the list of your books\n");
for ( index = 0; index < count; index++)
{
printf("%s by %s %.2f \n " , library[index].title,library[index].author,library[index].value);
}
}
else
{
printf("no books to bad \n");
}
system("pause");
}
结构体嵌套
#include<stdio.h>
#include <stdlib.h>
#define LEN 20
const char* msgs[5] =
{
"think you for the wonderot",
"you certainly prove that a ",
"is a special kind of guy . we must get together ",
"over a dilicious",
"and have a few laughs "
};
struct names{
char first[LEN];
char last[LEN];
};
struct guy
{
struct names handle;
char favfood[LEN];
char job[LEN];
float income ;
};
void main()
{
struct guy fellow =
{
"enwen",
"Villard",
"grolleds",
"personality coach ",
1500002.00
} ;
printf("Dear %s \n \n ",fellow.handle.first);
printf("%s %s \n ",msgs[0] , fellow.handle.first);
printf("%s %s \n ",msgs[1] , fellow.job);
printf("%s \n ",msgs[2] );
printf("%s %s %s \n ",msgs[3] , fellow.favfood,msgs[4]);
if (fellow.income > 1500000.0)
{
puts("!!");
}
else if(fellow.income > 75000.0)
{
puts("!");
}
else
{
puts(".");
}
printf("\n %40s %s \n" ," " ,"see you soon");
printf("\n %40s %s \n" ," " ,"shalala");
system("pause");
}
#include <stdio.h>
#include <stdlib.h>
#define LEN 20
struct names {
char first[LEN];
char last[LEN];
};
struct guy
{
struct names handle;
char favfood[LEN];
char job[LEN];
float income;
};
void main()
{
struct guy fellow[2] =
{{
"enwen",
"Villard",
"grolleds",
"personality coach ",
1500002.00
},{
"rodney",
"Swillbelly",
"tripe ",
"tabloid editor ",
23240.00
}} ;
struct guy *him;
printf("address 1 = %p address2 = %p \n" , &fellow[0], &fellow[1]);
him = fellow;
printf("address 1 = %p address2 = %p\n" ,him, him+1);
printf("him -> income = %f *him .income = %f\n",him->income,(*him).income);
him++;
printf("him -> income = %f *him .income = %f",him->income,(*him).income);
system("pause");
}
把结构成员作为参数传递
#include <stdio.h>
#include <stdlib.h>
#define FUNDLEN 50
struct funds
{
char bank [FUNDLEN];
double bankfund ;
char save[FUNDLEN];
double savefund;
};
double sum(double,double);
void main()
{
struct funds stan = {
"Garlic-melon Bank",
3023.72,
"Lucky's Saviings and Loa",
9237.11
};
printf("Stan has a total of %.2f.\n",sum (stan.bankfund,stan.savefund));
}
double sum(double x ,double y)
{
return x+ y;
}
传递指向结构体的指针
#include <stdio.h>
#include <stdlib.h>
#define FUNDLEN 50
struct funds
{
char bank [FUNDLEN];
double bankfund ;
char save[FUNDLEN];
double savefund;
};
double sum(const struct funds *);
void main()
{
struct funds stan = {
"Garlic-melon Bank",
3023.72,
"Lucky's Saviings and Loa",
9237.11
};
struct funds *p ;
p = &stan;
printf("Stan has a total of %.2f.\n",sum (p ));
}
double sum(const struct funds *money )
{
return money->bankfund + money -> savefund;
}
把结构体作为参数传递
#include <stdio.h>
#include <stdlib.h>
#define FUNDLEN 50
struct funds
{
char bank [FUNDLEN];
double bankfund ;
char save[FUNDLEN];
double savefund;
};
double sum(const struct funds );
void main()
{
struct funds stan = {
"Garlic-melon Bank",
3023.73,
"Lucky's Saviings and Loa",
9237.11
};
struct funds *p ;
p = &stan;
printf("Stan has a total of %.2f.\n",sum (stan));
}
double sum(const struct funds money )
{
return money.bankfund + money. savefund;
}
使用只想结构的指针
#include <stdio.h>
#include <stdlib.h>
#define FUNDLEN 50
struct funds
{
char fname[20];
char lname[20];
int letters;
};
void getinfo (struct funds * );
void makeinfo (struct funds * );
void showinfo (const struct funds * );
void main()
{
struct funds person;
getinfo(&person);
makeinfo(&person);
showinfo(&person);
}
void getinfo(struct funds * pst)
{
printf("please enter your first name \n");
gets(pst -> fname);
printf("please enter your last name \n");
gets(pst -> lname);
}
void makeinfo(struct funds *pst)
{
pst ->letters = strlen(pst ->fname)+ strlen(pst ->lname);
}
void showinfo(const struct funds * pst)
{
printf("%s %s your name contains %d letters \n " ,pst -> fname ,pst ->lname,pst->letters);
}
传递和返回结构
#include <stdio.h>
#include <stdlib.h>
#define FUNDLEN 50
struct funds
{
char fname[20];
char lname[20];
int letters;
};
struct funds getinfo (void );
struct funds makeinfo (struct funds );
voidshowinfo ( struct funds );
void main()
{
struct funds person;
person =getinfo();
person =makeinfo( person);
showinfo(person);
}
struct funds getinfo (void )
{
struct funds temp;
printf("please enter your first name \n");
gets(temp.fname);
printf("please enter your last name \n");
gets(temp.lname);
return temp;
}
struct funds makeinfo (struct funds info)
{
info.letters = strlen(info.fname)+ strlen(info. lname);
return info;
}
voidshowinfo ( struct funds pst )
{
printf("%s %s your name contains %d letters \n " ,pst.fname ,pst.lname,pst.letters);
}
使用指针和malloc
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
struct funds
{
char *fname ;
char *lname ;
int letters;
};
void getinfo (struct funds * );
void makeinfo (struct funds * );
void showinfo ( const struct funds *);
voidcleanup ( struct funds *);
void main()
{
struct funds person;
getinfo(&person);
makeinfo(&person);
showinfo(&person);
cleanup(&person);
}
void getinfo (struct funds * pst)
{
char temp[81];
printf("please enter your first name \n");
gets(temp);
pst ->fname = (char *) malloc(sizeof(temp)+1);
strcpy( pst -> fname, temp);
printf("please enter your last name \n");
gets(temp);
pst ->lname = (char *) malloc(sizeof(temp)+1);
strcpy( pst -> lname, temp);
}
void makeinfo (struct funds * info)
{
info->letters = strlen( info->fname)+ strlen( info-> lname);
}
void showinfo ( const struct funds *pst)
{
printf("%s %s your name contains %d letters \n " ,pst->fname ,pst ->lname,pst->letters);
}
void cleanup(struct funds *pst)
{
free(pst->fname);
free(pst->lname);
}
复合文字
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define MAXTITL 41
#define MINAUTL 41
struct book
{
char tittle[MAXTITL] ;
char author[MINAUTL] ;
float value;
};
void main()
{
struct book readfirst ;
int score ;
printf("please enter your score \n");
scanf("%d",&score);
if (score >= 84) {
readfirst = (struct book ){"Crime and punishment",
"Fyodor Dostoyevsky",
9.99};
}
else
readfirst =(struct book ){"mr bouncy's nice hat ",
"Fred winsome",
5.99};
printf("your assigned reading \n");
printf("%s by %s %.2f \n ",readfirst.tittle,readfirst.author,readfirst.value);
}
伸缩型数组成员
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
struct flex
{
int count ;
double average;
double scores[];
};
void showFlex(const struct flex *p);
void main()
{
struct flex *pf1 ,*pf2;
int n = 5;
int i;
int tot =0;
pf1 = (struct flex *)malloc(sizeof(struct flex )+n *sizeof(double));
//pf1 = malloc(sizeof(struct flex )+n *sizeof(double));
pf1->count = n;
for (i = 0 ; i < n ; i++) {
pf1 ->scores[i] = 20.0 -i;
tot += pf1 ->scores [i];
}
pf1 ->average = tot /n;
showFlex(pf1);
n =9;
tot =0;
pf2 = (struct flex *) malloc(sizeof(struct flex )+n *sizeof(double));
pf2 ->count = n;
for (i = 0 ; i < n ; i ++ ) {
pf2 ->scores[i] = 20.0 - i /2.0;
tot += pf2 ->scores[i];
}
pf2 ->average = tot/n;
showFlex(pf2);
free(pf1);
free(pf2);
}
void showFlex(const struct flex *p)
{
int i;
printf("score ");
for (i = 0 ; i < p->count; i++) {
printf("%g",p->scores[i]);
}
printf("\n Avergae %g \n",p->average);
}
//
//
//void getinfo (struct funds * pst)
//{
// char temp[81];
// printf("please enter your first name \n");
// gets(temp);
// pst -> fname = (char *) malloc(sizeof(temp)+1);
// strcpy( pst -> fname, temp);
// printf("please enter your last name \n");
// gets(temp);
// pst -> lname = (char *) malloc(sizeof(temp)+1);
// strcpy( pst -> lname, temp);
//
//}
//void makeinfo (struct funds * info)
//{
// info-> letters = strlen( info->fname)+ strlen( info-> lname);
//
//}
//void showinfo ( const struct funds *pst)
//{
// printf("%s %s your name contains %d letters \n " ,pst->fname ,pst ->lname,pst->letters);
//}
//void cleanup(struct funds *pst)
//{
// free(pst->fname);
// free(pst->lname);
//}
向 函数 传递 一个结构数组
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define FUNDLEN 50
#define N 2
struct funds
{
char bank [FUNDLEN];
double bankfund ;
char save[FUNDLEN];
double savefund;
};
double sum( const struct funds money[] ,int n);
void main()
{
struct funds jones[N]= {{"Garlic-melon bank ",3024.72,"Lucky's saving and loan ",9237.11 },{"Honset jack's bank ",3534.28,"party time savings ",3203.89}};
printf("The JOnese have total of %.2f \n",sum(jones, N));
}
double sum( const struct funds money[] ,int n)
{
double total;
int i;
for (i = 0 ,total = 0; i < n ; i++) {
total += money[i] .bankfund + money[i].savefund;
}
return total;
}
##include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define MAXTITL 41
#define MINAUTL 41
#define MAXBKS 10
struct book
{
char tittle[MAXTITL] ;
char author[MINAUTL] ;
float value;
};
void main()
{
struct book libarary[MAXBKS] ;
int count = 0;
int index , filecount;
FILE * pbooks;
int size = sizeof(struct book);
if ((pbooks = fopen(".//book.dat", "a+b")) == NULL) {
fputs("cant open book.dat file \n ", stderr );
exit(1);
}
rewind(pbooks);
while (count < MAXBKS && fread(&libarary[count], size, 1, pbooks) == 1 ) {
if (count == 0 ) {
puts("current contents of book.dat ");
}
printf("%s by%s %.2f \n ",libarary[count].tittle,libarary[count].author,libarary[count].value);
count++;
}
filecount = count;
if (count == MAXBKS) {
fputs("the book.dat file is full ", stderr);
exit(2);
}
puts("please add new book titles ");
puts("press enter at the start of line to stop ");
while (count < MAXBKS && gets(libarary[count].tittle) != NULL && libarary[count].tittle[0] != '\0' ) {
puts("now enter the author ");
gets(libarary[count].author);
puts("now enter the value ");
scanf("%f",&libarary[count ++ ].value);
while (getchar()!= '\n') {
continue;
}
if (count < MAXBKS) {
puts("enter the next title");
}
}
if (count > 0) {
puts("here is the list of your books ");
for (index = 0; index < count ; index ++ ) {
printf("%s by%s %.2f \n ",libarary[index].tittle,libarary[index].author,libarary[index].value);
}
fwrite(&libarary[filecount], size, count - filecount, pbooks);
}
else puts("no books too bad \n");
puts("bey\n");
fclose(pbooks);
}
使用枚举值( 编译失败)
#include <stdio.h>
#include <string.h>
#include <stdbool.h>
enum spectrum{ red,orange , yellow ,green,blue,violet};
const char * colors[]={ "red","orange" , "yellow" ,"green","blue","violet"};
#define LEN 30
int main()
{
char choice[LEN];
enum spectrum color;
bool color_is_found=false;
puts("Enter a color (empty line to quit)");
while (gets(choice) != NULL && choice[0] != '\0')
{
for (color = red ; color <= violet ; color++) {
if (strcmp(choice, colors[color]) == 0) {
color_is_found =true;
break;
}
}
if (color_is_found) {
switch (color) {
case red:
puts("Roses are red ");
break;
case blue:
puts("Roses are red ");
break;
case yellow:
puts("Roses are yellow ");
break;
case green:
puts("Roses are green ");
break;
case violet:
puts("Roses are violet ");
break;
case orange:
puts("Roses are orange ");
break;
default:
break;
}
}
else
printf("I Dont know about the color %s ",choice);
color_is_found =false;
puts("Next color p;ease (empty line to quit )");
}
puts("Goodbye");
}
使用函数指针
#include <stdio.h>
#include <string.h>
#include <ctype.h>
char showmenu();
void eatline();
void show(void(*fp) (char) , char * str);
void ToUpper(char*);
void ToLower(char *);
void Transpose(char *);
void Dummy(char *);
void main()
{
char line [81];
char copy [81];
char choice;
void (*pfun)(char *);
puts("Enter a string (empty ine to quit )");
while (gets(line) != NULL && line[0] != '\0') {
while ((choice = showmenu() ) != 'n') {
switch (choice) {
case 'u':
pfun =ToUpper ;
break;
case 'l':
pfun =ToLower ;
break;
case 't':
pfun =Transpose ;
break;
case 'o':
pfun =Dummy ;
break;
}
strcmp(copy, line);
show(pfun, copy);
}
puts("enter a string emty line to quite " );
}
puts("bey");
}
char showmenu(void)
{
char ans;
puts("Enter menu choice ");
puts("u ) uppercase 1 ) lowercase ");
puts(" T ) transposed case o ) original case ");
puts("n) next tring ");
ans =getchar();
ans =tolower(ans);
eatline() ;
while (strchr("ulton ", ans) == NULL) {
puts("please enter a u l t o or n ");
ans =tolower(getchar());
eatline() ;
}
return ans;
}
void eatline ()
{
while (getchar() != '\n') {
continue;
}
}
void ToUpper(char *str)
{
while (*str) {
*str =toupper( *str);
str++;
}
}
void ToLower (char *str)
{
while (*str) {
*str =tolower( *str);
str++;
}
}
void Transpose (char *str)
{
while (*str) {
if (islower(*str)) {
*str =toupper(*str );
}
else if (isupper(*str))
{
*str =tolower(*str);
}
str++;
}
}
void Dummy(char * str)
{
}
void show(void(*fp) (char) , char * str)
{
(*fp)(str);
puts(str);
}