0

I want to copy player names and numbers in a 2D array which has 5 columns.

Expected output after loading data to the array:

1234
Real Madrid
Courtois 1
Carvajal 2
Alaba 4
Marcelo 12
Kross 8

5678
Paris Saint Germain
Hakimi 2
Ramos 4
Mbappe 7
Messi 30
Neymar 10

6547
Manchester United
Ronaldo 7
Pogba 6
Sancho 25
Cavani 21
Matic 31
#include <stdio.h>
#include <string.h>
typedef struct {
    char team_name[25];
    int team_id;
    char player_name[8][8]; 
    char player_number[8][4]; // considering player's names as a string
}Team;
int CopyToArray(Team t[]) {
FILE* p; 
char c;
int i = 0;
p = fopen("team.txt" , "r");
   if (p == NULL) {
     printf("ERROR! FILE CANNOT BE OPENED !\n");
   }
   else {
       while (!(feof(p))) {
       fgets(t[i].team_name, 25, p);
       fscanf(p, "%d", &t[i].team_id);
       c = getc(p); // read the '\n'
       for (int j=0; j<5; ++j) {
       fscanf(p, "%s%s", t[i].player_name[j], t[i].player_number[j]);
       }
  
       ++i; // to return the number of teams
     }
       fclose(p);
   }
   return i;
}
void print(Team t[], int n) {
    printf("DATA IN THE ARRAY: \n");
       for (int i=0; i<n; ++i) {
       printf("%s", t[i].team_name);
       printf("%d", t[i].team_id);
         for (int j=0; j<5; ++j) {
         printf("%s %s\n",t[i].player_name[j], t[i].player_number[j]);
         }
       }
     }
int main (void) {
Team s[100];
int res = CopyToArray(s);
print(s, res);
return 0;
}
philipxy
  • 14,867
  • 6
  • 39
  • 83
Bilal
  • 23
  • 3
  • 1
    `fgets` reads the newline so the `getc` isn't necessary. You'll want to remove it from the team name though so [Removing trailing newline character from fgets() input](https://stackoverflow.com/questions/2693776/removing-trailing-newline-character-from-fgets-input) You want to change the scanf right after `fgets` to `fscanf` to read from the file instead of stdin. `fscanf` does not read the newline so you either need to consume it after the last `fscanf` or perhaps only use `fgets` to read lines and `sscanf` to parse them. – Retired Ninja Feb 26 '22 at 19:20
  • 1
    Note that [`while (!feof(file))` is always wrong](https://stackoverflow.com/questions/5431941/while-feof-file-is-always-wrong). – Jonathan Leffler Feb 26 '22 at 19:29
  • Your random indentation scheme makes it hard to read your code. You'll probably want at least a space separating the team name from the team ID, and you should probably separate the team ID from the first player with a newline. You should be checking that the `fgets()` and `fscanf()` calls succeed, taking appropriate evasive action if they do not. – Jonathan Leffler Feb 26 '22 at 19:30

0 Answers0