0

该代码用于创建商店购买、库存维护系统 我在使用 fscanf(fp,............) 函数将数据从 txt 文件输入到链表时遇到问题;

下面的代码有问题写在评论部分,但简而言之,当我在 turbo c 中运行代码并在运行时输入数据时,如果我没有读取旧内容,内容会正确进入文件。每次我打开程序时,文件都会被覆盖。 当我用 fscanf() 读取内容时,垃圾值开始添加到文件中,我不知道为什么。可能是因为我使用的是指针而不是对象,但我不知道另一种方式。

我知道我的程序效率低下,但我仍然想知道代码有什么问题以及如何解决它我使用了很多变量,其中一些可能永远不会使用,请原谅我。代码中的问题会在create函数中发现:

#include<alloc.h>
#include<stdio.h>
#include<conio.h>
#include<string.h>
#include<graphics.h>
#define size 20
struct shop{
char name[size];
int quantity;
int price;
struct shop *next;
}*start;
typedef struct shop sh;

char u_name[30];
char u_pass[30];

int i,user,password;
int k=0,l=0;
char add_more;
char c,choice,c1,more;




void create()
{ FILE *fc,*fp;

struct shop *ptr,*temp,*g,*l,*m,*t,*i,*d;
char ch,v[20];
int r,z,w,flag=0;
//the code ***************from here******************
fc=fopen("storedata.txt","r");
d=(sh*)malloc (sizeof(sh));
d->next=NULL  ;
i=d;
m=d;


while(fscanf(fc,"%s\t%d\t%d",m->name,m->quantity,m->price)!=EOF)
{
d=(sh*)malloc (sizeof(sh));
m->next=d;
m=m->next;

}
m->next=NULL;
fclose(fc);

t=i;

clrscr();
printf("NAME\t\t\tQUANTITY\t\t\t\tPRICE(RS)");

do
{
printf("\n%s ",t->name);
printf("\t\t\t%-20d",t->quantity);
printf("\t\t\t%-40d",t->price);
t=t->next;
}while(t!=NULL);
 getch();
 getch();
//*************till here********the smaller code part above is the code to read in the file which doesnt work correctly
start=i;}  // when i remove this line all the values entered in the file are correct but file is overridden every time i run it

谢谢

4

2 回答 2

1

与 scanf 一样,fscanf 需要存储由 format 参数表示的信息的位置/地址。以下用法不正确:

fscanf(fc,"%s\t%d\t%d",m->name,m->quantity,m->price);

由于既不是有效地址m->quantity也不m->price是有效地址,您应该使用&运算符:

fscanf(fc,"%s\t%d\t%d",m->name,&m->quantity,&m->price);
于 2013-05-03T14:17:21.200 回答
1

您的返回值处理fscanf()已关闭。

它不返回指针,它返回一个int请参阅文档。整数是成功转换的次数;您应该将该值与%格式字符串中的说明符数量相匹配。

它需要指向数据应该存储在哪里的指针;像这样的整数转换%d需要一个地址int,即&m->quantity在您的代码中。

不要malloc()在C中强制转换返回值。实际上,重新编写

d=(sh*)malloc (sizeof(sh));

作为:

d = malloc(sizeof *d);

以提高清晰度、减少重复和更简洁。

于 2013-05-07T08:37:31.083 回答