【发布时间】:2015-12-12 08:33:49
【问题描述】:
所以这里基本上我有两个循环,它们基本上做同样的事情,除了它们 fscanf 到不同的目录。 第二个应该 fscanf 到一个结构,一个会导致程序崩溃。 这是为什么????? 导致程序崩溃的代码是程序中最后一个for循环。
#include <stdio.h>
#include <conio.h>
#include <string.h>
#define MAXLEN 100
int main()
{
char filename1[MAXLEN];
char filename2[MAXLEN];
char filename3[MAXLEN];
char filename4[MAXLEN];
char itemname[MAXLEN];
printf("Enter the input file: ");
scanf("%s", filename1);
strcpy(filename3,filename1);
strcat(filename3,"Output.txt");
strcpy(filename4,filename1);
strcat(filename4,"Log.txt");
strcpy(filename2, filename1);
strcat(filename2, "Customers.txt");
strcat(filename1, ".txt");
printf("%s will be used",filename1);
FILE *inputfile1 = NULL;
FILE *inputfile2 = NULL;
FILE *outputfile = NULL;
FILE *logfile = NULL;
inputfile1 = fopen(filename1, "r");
inputfile2 = fopen(filename2, "r");
outputfile = fopen(filename3, "w");
logfile = fopen(filename4, "w");
int numberofitems =0;
while (fscanf(inputfile1,"%s",itemname)==1){
numberofitems++;
}
rewind(inputfile1);
numberofitems /= 4;
struct storestock{
char itemnames[numberofitems][MAXLEN];
int isdecimal[numberofitems];
double stock[numberofitems];
double price[numberofitems];
};
typedef struct storestock store;
store inventory;
int i;
for (i=0; i < numberofitems; i++)
{
fscanf(inputfile1,"%s %d %lf %lf",inventory.itemnames[i],&(inventory.isdecimal[i]),
&(inventory.stock[i]),&(inventory.price[i]));
printf("\n %dst item %s %d %lf %lf", i+1,inventory.itemnames[i],inventory.isdecimal[i]
,inventory.stock[i],inventory.price[i] );
}
struct customers{
char customername[MAXLEN];
char wanteditems[10][MAXLEN];
double amountwanted[10];
};
int j,k,l;
int numberofcustomers = 0;
int itemnumber=0;
double itemamount;
char string[MAXLEN];
for (j=0;j<100;j++){
if (fscanf(inputfile2,"%s %lf", string,&itemamount)==1){
numberofcustomers++;
printf("\n%s",string);
}}
printf("%d", numberofcustomers);
struct customers mycustomers[numberofcustomers];
rewind(inputfile2);
**for (k=0;k<100;k++){
if (fscanf(inputfile2,"%s %lf", mycustomers[k].customername,&itemamount)==1){
printf("\n%s", mycustomers[k].customername);}
}**
getch();
return 0;
}
【问题讨论】:
-
试试
for(k = 0; k < numberofcustomers; k++) -
帅哥没用
-
printf("%d", numberofcustomers);显示什么?是零吗?因为numberofcustomers++行位于if块内,该块的条件看起来很可疑,if (fscanf(inputfile2,"%s %lf", string,&itemamount)==1)。fscanf读取 两个 输入,但随后检查是否只读取了 一个。因此,假设输入文件格式正确,这意味着条件永远不会为真,因此numberofcustomers将为零。 -
@CoolGuy 我不确定这是否有效。
numberofcustomers在运行时从文件中确定。我认为 C 在编译时确定大小,而不是在运行时。