我必须先阅读一个txt文件,以描述问题的第一行。它可以是a或b,然后我有一些整数并作为矩阵。我的程序对两者都适用,但是有些文件在第一个问题出现后可能会有另一个格式相同的文件。我不知道该怎么做。帮助请。
txt样本:
5 5 A(B) 1
0 3 (start point)´
1 5 6 5 9
5 8 6 3 1
8 6 9 5 3
5 6 9 3 0
2 3 9 3 8
然后是这种格式的另一个或更多问题
while(!feof(fp)){
fscanf(fp, "%d %d %c %d", &L, &C, &variante, &pontos);
mapa=(int **)malloc(L*sizeof(int*));
for(i=0; i<L; i++){
mapa[i]=(int*)malloc(C*sizeof(int));
}
for(i=0; i<L; i++){
for(j=0; j<C; j++){
mapa[i][j]=0;
}
}
if(variante == 'A') {
fscanf(fp, "%d %d", &Linit, &cinit);
for(i=0; i<L; i++){
for(j=0; j<C; j++){
fscanf(fp, "%d", &mapa[i][j]);
printf("%d-", mapa[i][j]);
}
printf("\n");
}
possivel=varianteA(mapa, L, C, Linit, cinit, &custo);
printf("%d\n",custo);
}
if(variante== 'B'){
line=(int*)malloc(pontos*sizeof(int));
col=(int*)malloc(pontos*sizeof(int));
for(k=0; k<pontos; k++){
line[k]=0;
col[k]=0;
}
for(k=0; k<pontos; k++){
fscanf(fp, "%d %d", &line[k], &col[k]);
}
for(i=0; i<L; i++){
for(j=0; j<C; j++){
fscanf(fp, "%d", &mapa[i][j]);
printf("%d-", mapa[i][j]);
}
printf("\n");
}
possivel=varianteB(mapa, L, C, &custo, pontos, line, col);
printf("%d %d\n", possivel, custo);
free(line);
free(col);
}
for(i=0; i<L; i++){
int *linha;
linha=mapa[i];
free(linha);
}
free(mapa);
}
// free(variante);
fclose(fp);
现在我有了这个,但是它还存在另一个问题,它不在文件中。 valgrind给我一个错误:possivel = varianteA(..)。它说地址是在分配了siz 24的块之后为0字节
答案 0 :(得分:1)
在解决此类问题(或实际上是任何编程任务)时,写一些伪代码通常是有益的,只是用文字说明程序需要做什么。
做问题
(编辑:看来我已经达到了缩进级别的上限,但是您明白了)
因此,现在该问题被分解为更小的,希望更易于管理的问题。
答案 1 :(得分:0)
以下是一些有关如何构造程序的示例sudo代码。您将不得不进行大量修改,但是您只需要阅读第二个问题即可。
#define MAX_SIZE (100) //or whatever it is
#define UNIQUE_IDENTIFIER "=" //or whatever it is
FILE * fp = NULL;
int problem_counter = 0;
char * line = malloc(sizeof(char)*MAX_SIZE);
if(!(fp = fopen("problem.txt","r"))){
do_error_handling();
}
do{
printf("This is the %dth problem", ++problem_counter); //dont need to printf this but you can start counting here.
if(fgets(line,MAX_SIZE,fp) == NULL){
break;
}
if(strstr(line,UNIQUE_IDENTIFIER){
//start of problem. maybe read in all the lines here and build up the problem you have to solve
read_problem(line); //does special stuff based of the first line read
solve_problem(); //solve the problem based on the stuff you extracted from reading the problem
}
while(!feof(fp));