Home > Net >  Using fgets with struct
Using fgets with struct

Time:10-29

I get the following error suggestion:

note: expected 'char *' but argument is of type 'int *' _CRTIMP __cdecl __MINGW_NOTHROW char * fgets (char *, int, FILE *);

Which is related to the t->name etc I am guessing, is there any way around this.

Also right now the wins and losses are stored weirdly and the program works like this:

inputs:
Name of team > goo
Wins of team > 3
Losses of team > 4
Name of team > goo
Wins of team > 4
Losses of team > 3

outputs
team 1 name is goo

team 2 name is goo

Here is my code

#include <stdio.h>
#include <stdlib.h>
#include <string.h>


#define MAX_SIZE 20
#define MAXC 1024

typedef struct {
    char name[MAX_SIZE];
    char wins[MAX_SIZE];
    char losses[MAX_SIZE];
} teams;


int addteam(teams *t);


int addteam(teams *t) {
    char buffer[MAXC];


    printf("Name of team > ");
    fgets(t->name, MAXC, stdin);

    printf("Wins of team > ");
    getchar();
    fgets(t->wins, MAXC, stdin);

    printf("Losses of team > ");
    getchar();
    fgets(t->losses, MAXC, stdin);

    return 0;
}


int main() {
    int numOfTeams;
    char array[MAX_SIZE];
    char * Ptr;

    teams team[MAX_SIZE] = {{ .name = "", .wins = 0, .losses = 0}}; 
    for(int i=0; i < 2; i  ) {
        addteam( &team[i] );
    }

    for(int j=0; j<2; j  ) {
        printf("team %d name is %s   %s    %s\n",j 1, team[j].name, team[j].wins, team[j].losses);
    }

}



CodePudding user response:

fgets reads lines of text into a char buffer. fgets knows nothing about numbers.

Replace

fgets(t->wins, MAXC, stdin);

with

char buffer[100];  // temporary buffer for line containing a number
fgets(buffer, sizeof(buffer), stdin);  // read line
t->wins = atoi(buffer);                // extract number

Do the same for t->losses. You probably should put this in a function such as int ReadIntFromLine(FILE *input).

Disclaimer:

Instead of atoi we could use strtol which is a better alternative for real world programs as it allows to detect malformed input.

  •  Tags:  
  • c
  • Related