C语言结构体的问题,一个嵌套,可是我写的好像有问题,初学求帮助解答,谢谢

#include <stdio.h>
#define total 2
struct author {
char FirstName[20];
char LastName[20];
char sex[10];
};
struct book {
char title[20];
float value;
struct author author;
};
int main() {
int i; for( i=0;i<total;i++)
{
printf("输入这本书的标题:");
scanf("%c",&book.title);
printf("输入这本书的价钱:");
scanf("%f",&book.value);
printf("输入这本书的作者姓和名:"); scanf("%c%c",&author.FirstName,&author.LastName);
printf("输入作者的性别:");
scanf("%c",&author.sex);
}
printf("标题:%c\n",&book.title);
printf("价格:%f\n",&book.value);
printf("作者的姓和名:%c%c\n",&author.FirstName,&author.LastName); printf("作者的性别:%c\n",&author.sex);
return 0;
}

你要用结构的要先定义一个结构的变量。
book结构里面的 struct author author; 这个结构变量定义变量名不要和结构类型名字一样。
struct book a; //book是类型名字。后面的a才是变量名。
scanf的输入格式控制符。%c是一个字符。如果是字符串的话是%s。
还有printf后面的参数表不要加地址符&;
还有那个循环是无意义的。。。输入两次。第二次覆盖第一次。
#include <stdio.h>
struct author
{
char FirstName[20];
char LastName[20];
char sex[10];
};
struct book
{
char title[20];
float value;
struct author bk;
};
int main()
{
int i;
struct book p;
printf("输入这本书的标题:\n");
scanf("%s",&p.title);
printf("输入这本书的价钱:\n");
scanf("%f",&p.value);
printf("输入这本书的作者姓和名:\n");
scanf("%s%s",&p.bk.FirstName,&p.bk.LastName);
printf("输入作者的性别:\n");
scanf("%s",&p.bk.sex);
printf("标题:%s\n",p.title);
printf("价格:%f\n",p.value);
printf("作者的姓和名:%s%s\n",p.bk.FirstName,p.bk.LastName);
printf("作者的性别:%s\n",p.bk.sex);
return 0;
}
温馨提示:内容为网友见解,仅供参考
第1个回答  2012-03-10
#include <stdio.h>
#include <string.h>

struct author {
char FirstName[20];
char LastName[20];
char sex[10];
};

struct book {
char title[20];
float value;
struct author aut; //变量名别和结构体名一样
};

int main() {
struct book boo;
char first[20],last[20],titl[20],se[10];
printf("输入这本书的标题:\n");
scanf("%s",titl);
strcpy(boo.title, titl); //注意字符串拷贝要用这个函数

printf("输入这本书的价钱:\n");
scanf("%f",&boo.value);

printf("输入这本书的作者姓和名:\n");
scanf("%s",first);
scanf("%s",last);
strcpy(boo.aut.FirstName, first);
strcpy(boo.aut.LastName, last);

printf("输入作者的性别:\n");
scanf("%s",se);
strcpy(boo.aut.sex, se);

printf("标题:%s\n",boo.title);
printf("价格:%f\n",boo.value);
printf("作者的姓和名:%s %s\n",boo.aut.FirstName,boo.aut.LastName);
printf("作者的性别:%c\n",boo.aut.sex);
return 0;
}
第2个回答  2012-03-10
%c是输入单个字符的,你确定姓名和书名都是用的单个字符吗?建议你改成gets(author.FirstName);
或者scanf("%s", author.FirstName);
%c会接收包括空格和回车在内的各种字符……追问

谢谢,可是还是不能输出,不晓得为什么啊

追答

你的book是结构体名而不是变量名,你需要再定义一个,比如struct book b;
然后输入、输出用b.xxx

本回答被提问者采纳
相似回答