首页 > 解决方案 > 将 fget 与结构一起使用

问题描述

我收到以下错误建议:

注意:预期为 'char *' 但参数的类型为 'int *' _CRTIMP __cdecl __MINGW_NOTHROW char * fgets (char *, int, FILE *);

这与我猜的 t->name 等有关,有什么办法可以解决这个问题。

现在,输赢的存储也很奇怪,程序的工作方式如下:

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

这是我的代码

#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);
    }

}



标签: c

解决方案


fgets将文本行读入 char 缓冲区。fgets对数字一无所知。

代替

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

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

对 做同样的事情t->losses。你可能应该把它放在一个函数中,比如int ReadIntFromLine(FILE *input).

免责声明:

而不是atoi我们可以使用strtol哪个是现实世界程序的更好替代方案,因为它允许检测格式错误的输入。


推荐阅读