读书人

帮小弟我看一下这个结构体程序错在哪

发布时间: 2013-07-16 22:38:05 作者: rapoo

帮我看一下这个结构体程序,错在哪里,输出时不正常。
下面这个程序是将一个结构体内容读进一个文件,然后再从文件读取到另一个同类型结构体变量,同时增加一点内容后再输出。但是输出时有乱码,不知错在哪里?请帮忙。

#include "stdafx.h"
#include "stdio.h"
#include "string.h"
#include "stdlib.h"

#define SIZE 20
#define NUMBER 5

struct book
{
char bookname[SIZE];
char authorname[SIZE];
float price;
};

int main(void)
{
struct book library[3] = {
{"aaa", "Tom", 20.00},
{"bbb", "Mary", 15.00},
{"ccc", "Jack", 25.00},
//{"ddd", "Florence", 23.00},
//{"eee", "Jim", 21.00}
};
struct book library_2[NUMBER];
FILE *pf;
int count = 0;

//将结构体读入文件f:\\123.txt中
pf = fopen("f:\\123.txt", "w+b");
if(pf == NULL)
{
fprintf(stderr, "Can not open the file.\n");
exit(1);
}
else
{
fwrite(library, sizeof(library), 1, pf);
}
fclose(pf);
//将文件f:\\123.txt写入结构体library_2[NUMBER]中;

pf = fopen("f:\\123.txt", "rb");
if(pf == NULL)
{
fprintf(stderr, "Can not open the file.\n");
exit(1);
}
else
{
while(fread(library_2, sizeof(struct book), 1, pf) == 1)
{
count++;
}
}

//如果library_2没有满就继续增加书本。
if(count == NUMBER)
{
puts("the library_2 is full.");
}
else
{
puts("Please add books to library_2 (press [ENTER] at the start of a line to quit):");
puts("Please input the name of the book:");
while(count<NUMBER && gets(library_2[count].bookname)!=NULL && library_2[count].bookname[0]!= '\0')
{
puts("Now input the name of the author:");
gets(library_2[count].authorname);
puts("Now input the price of the book:");
scanf("%f", &library_2[count].price);
rewind(stdin);
count++;
if(count < NUMBER)
{
puts("Please input another book's information (press [ENTER] at the start of a line to quit):");
}
}
}

//显示library_2的书本。
for(int i=0; i<count; i++)
{
printf("the boook %s written by %s is wroth %.2f.\n", library_2[i].bookname, library_2[i].authorname, library_2[i].price);


}

return 0;
}



[解决办法]
数组读取越界了吧,还是没有以\0结尾?
[解决办法]
while(fread(library_2, sizeof(struct book), 1, pf) == 1)
错了你,读取数据后一直往library_2[0]中方数据,当然只能读取文件中最后一个数据啊,其他为乱码

[解决办法]

for(int i=0;i<3;i++){
fread(library_2+i, sizeof(struct book), 1, pf);
count++;
}
你在试试

[解决办法]
你这里读的时候, 每次都读到数组的第一个去了啊:

while(fread(library_2, sizeof(struct book), 1, pf) == 1)
{
count++;
}

改成下面这样试试:
while(fread(&library_2[count], sizeof(struct book), 1, pf) == 1)
{
count++;
}

[解决办法]
fread(library_2, sizeof(struct book), 1, pf) == 1
有错

读书人网 >C语言

热点推荐