我已经阅读了该站点上的几个问题,并设法编写了下面的代码,该代码从文件中读取数据(如下所示的代码之前)。问题是代码在段中进入无限循环do {...} while
,表明它不能“识别”换行符。我不知道该怎么做。此外,当我从命令行传递要读取的文件名时,它会崩溃。有人可以帮忙吗?
输入文件格式:
1 3
3
3 1 23588769 1 2 1 4
4 9 4788939 3 2 1 2 2 4 5 5 2 3 3 1 4
3 5 17215766 5 2 1 1 4 5 5 4
代码:
int main (int argc, char *argv[])
{
FILE *fp = NULL;
if (argc == 1)
{
fp = stdin;
}
else
{
fp = fopen( argv[1], "r" ) ;
}
fp = fopen( argv[1], "r" ) ;
if (fp == NULL) exit(2);
for(i=0; i<42; i++)
KEYS_I_HAVE[i]=0;
fscanf( fp,"%d",&num_start_keys);
fscanf(fp, "%d",&doors);
KEYS_FOR_DOORS = (int*)malloc(doors*sizeof(int));
POINTS = (int*)malloc(doors*sizeof(int));
for(i=0; i<doors; i++)
{
KEYS_FOR_DOORS[i]=0;
POINTS[i]=0;
}
MAP = malloc(doors*sizeof(int));
for(i=0; i<43; i++)
MAP[i] = malloc(43*sizeof(int));
for(i=0; i<doors; i++)
{
for (j=0; j<43; j++)
MAP[i][j] = 0;
}
for(i=0; i<(doors+1); i++)
{
j=0;
if(i==0)
{
do
{
fscanf(fp,"%d",&temp);
printf("%d",temp);
KEYS_I_HAVE[temp]++;
a=fgetc(fp);
}while(a != '\n');
}
else
{
do
{
fscanf(fp,"%d",&temp);
if (j==0)
sum += temp;
else
{
if (j==1)
KEYS_FOR_DOORS[i-1] = temp;
else
{
if(j==2)
POINTS[i-1]=temp;
else
MAP[i-1][temp]++;
}
}
a=fgetc(fp);
j++;
if (feof(fp) ) break;
}while( a != '\n' );
}
}
fclose(fp);