1

次のようにフォーマットされた約2000行のテキストのテキストファイルがあります。

1 1 Name1 LastN1 58 c 1600 1310.40 6 1 0.22 2164.80 1
2 1 Name2 LastN2 22 d 1700 1523.37 4 1 0.13 897.26 1 3 1 Name3
LastN3 34 c 1600 1195.84 2 1 3 0.216 8 . 2000 3 NameX LastNX 46 d 6000 6000.00 1 0 0.00 0.00 1


私がしたいのは、テキストファイルからこれらすべての値を読み取り、それらを次のような配列に格納することです:

int id          [2100];
char nombre [2100][30];
char apellido   [2100][30];
int edad        [2100];
int puesto      [2100];     char categoria  [2100];
int sueldoI     [2100];
float sueldoA   [2100];
int antiguedad  [2100];
int inscrito    [2100];
float aporte    [2100];
float ahorro    [2100]; 
int libre       [2100];

しかし、それらを読もうとすると、コンソールに大量のゴミが表示されます

これらは、私がそれらを読み取って配列に格納しようとするために使用している方法です:

//Way number 1
char linea[70];
while(fgets(linea,70,datos) != NULL){   
    flushall();
    sscanf(linea,"%d %d %s %s %d %c %d %f %d %d %f %f %d\n",&id[i],&puesto[i],&nombre[i],&apellido[i],&edad[i],&categoria[i],&sueldoI[i],&sueldoA[i],&antiguedad[i],&inscrito[i],&aporte[i],&ahorro[i],&libre[i]);      
    i++;
}

// Way number 2 in here i get linea the way it's intended to be but i can't figure
// out a way to split the string into the multiple values i need to store in the arrays

while(fgets(linea,70,datos) != NULL){
    printf("%s",linea);
}

これは私が最初の方法で得た出力です:

ウェイ #1 出力

編集:

配列のサイズを 2100 から 2000 に変更したところ、プログラムの動作が改善されたようです

4

1 に答える 1

5

&nombre[i]、およびから address-of 演算子を削除します&apellido[i]。これらは配列であり、address-of なしで配列名を使用して、最初の要素のアドレスを取得できます。

sscanf(/*....*/, nombre[i], apellido[i], /*....*/);

また、文字列の場合、予想される文字列の長さを scanf に指定する必要があります (配列のサイズ - 1):

sscanf(linea, "... %29s %29s ....", /*....*/, nombre[i], apellido[i], /*....*/);

そして、あなたは誤用しているかもしれませんi:

int main() {
  char linea[70];
  FILE *datos = fopen("datos", "r");
  int i= 0;
  while(fgets(linea,70,datos) != NULL){   
    sscanf(linea,"%d %d %29s %29s %d %c %d %f %d %d %f %f %d\n", &id[i], &puesto[i], 
        nombre[i], apellido[i],&edad[i],&categoria[i],&sueldoI[i],
        &sueldoA[i],&antiguedad[i],&inscrito[i],&aporte[i],&ahorro[i],   
        &libre[i]); 
    i++;
  } 

  i--;

  for (; i >= 0; i--) {
    printf("%d %s\n", id[i], nombre[i]);
  }

  return 0;
}
于 2012-07-12T04:58:00.530 に答える