关于C Primer Plus 一个结构体数组的例子
#include<stdio.h>#define MAXTITLE 2 //标题#define MAXAUTL 2 //作者#define MAXBKS 2 //最多可以容纳图书册数struct book //建立book模板{ char title[MAXTITLE]; char author[MAXAUTL]; float value;};int main(void){ struct book library[MAXBKS]; int count=0; int index; printf("please enter the books title.\n"); printf("please [enter] at the start of aline to stop.\n"); while(count<MAXBKS && gets(library[count].title)!=NULL && library[count].title[0]!='\0') { printf("Now enter the book 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("Enter the next 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 book? Too bad!"); return 0;}
lease enter the books titleplease [enter] at the start of aline to stop111Now enter the book authorkkkNow enter the value12Enter the next title222Now enter the book authoreeeNow enter the value32Here is the list of your books[color=#FF0000]11kk by kk: $ 12.00 应该是;111 by kkk &12.0022ee by ee: $ 32.00 222 by eee &32.00[/color]
#include<stdio.h>#define MAXTITLE 4 //这里#define MAXAUTL 4 //这里#define MAXBKS 2 //最多可以容纳图书册数struct book //建立book模板{ char title[MAXTITLE]; char author[MAXAUTL]; float value;};int main(void){ struct book library[MAXBKS]; int count=0; int index; printf("please enter the books title.\n"); printf("please [enter] at the start of aline to stop.\n"); while(count<MAXBKS && gets(library[count].title)!=NULL && library[count].title[0]!='\0') { library[count].title[MAXTITLE-1] = '\0'; //输出字符串得在字符数组末尾加'\0' printf("Now enter the book author.\n"); gets(library[count].author); library[count].author[MAXAUTL-1] = '\0'; printf("Now enter the value.\n"); scanf("%f",&library[count++].value); while(getchar()!='\n') continue; if(count<MAXBKS) printf("Enter the next 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 book? Too bad!"); return 0;}
[解决办法]
#define MAXTITLE 5 //标题
#define MAXAUTL 5 //作者
试试 是不是能达到效果
[解决办法]
struct book //建立book模板
{
char title[MAXTITLE];
char author[MAXAUTL];
float value;
};
title 和 author 都是拥有两个char类型变量的数组
library[count].title 和
library[count].author 字符宽度都是2
所以只读入了两个字符
[解决办法]
程序中没有检查输入字符串的最大长度是否超过结构中定义变量所能容纳的最大长度。
#define MAXTITLE 2 //标题
#define MAXAUTL 2 //作者
#define MAXBKS 2 //最多可以容纳图书册数
struct book //建立book模板
{
char title[MAXTITLE];
char author[MAXAUTL];
float value;
};
title最大可以容纳1个字符和1个'\0'串结束符。
author最大可以容纳1个字符和1个'\0'串结束符。