请问我的这个结构体程序在输出部分问题在哪里?
下面这个结构体程序是要建立一些图书信息,有书名,作者名,价格三个成员。我在输入部分能够顺利进行,但是在输出部分就会有乱码,我想问题应该出现在我的那个while循环的终止程序上,但是我不知道怎么改?求助。
#include "stdafx.h",
#include "stdio.h"
#include "string.h"
#define SIZE 100
#define NUMBER 10
struct book
{
char bookname[SIZE];
char authorname[SIZE];
float price;
};
int main(void)
{
struct book library[NUMBER];
int count = 0;
int index;
struct book *p;
p = library;
printf("Please enter the books' name ");
printf("and press [enter] at the start of a line to stop.\n");
while(count<NUMBER && gets(p->bookname)!= NULL
&& (p->bookname[0])!='\0')
{
printf("Now enter the author's name.\n");
gets(p->authorname);
printf("Now enter the price.\n");
scanf("%f", &p->price);
count++;
p++;
getchar();
if(count < NUMBER)
{
printf("Enter the next book's information.\n");
}
}
if(count > 0)
{
printf("There are %d books.The information of books are as follow:\n", count);
printf("book's name author's name the price of the book\n");
int i = 0;
while(i<count)
{
printf("%6s%13s%20.2f\n", p->bookname, p->authorname, p->price);
p++;
}
}
else
{
printf("No book. It is too bad.\n");
}
return 0;
}
[解决办法]
在输出之前加以下一行:
p = library;
[解决办法]
注意,你在开头建立的book数组,它不保证自己内容是初始化的。所以你的循环就很可能会出错。
你应当像对待一个对象那样对待结构体,为它设立一个初始化函数:
void book_init(struct book* self)
{
size_t i = 0;
for (; i<SIZE; i++)
{
self->bookname[i] = 0;
self->authorname[i] = 0;
}
self->price = 0;
}
[解决办法]
觉得你应该在int i=0;后面加一句,p=library;。像2楼所说的
[解决办法]
p 的位置以及改变了. 重新回去原来的位置就可以正确输出.