c - 将 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);
}
}
解决方案
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
哪个是现实世界程序的更好替代方案,因为它允许检测格式错误的输入。
推荐阅读
- c# - 建立关系分组表达式树c#
- html - 如何使用 bookdown::gitbook 作为输出来证明 Rmd 中的整个文本的合理性
- sql - 如何在 Oracle 中使用分组集重命名列
- python - 解决关于 dtype 是对象的 MultiIndex 错误
- laravel - Laravel:表用户没有名为 updated_at 的列
- spinnaker - 如何使用 spinnaker 更新管道定义 API
- cplex - 如何在 B&B 执行期间暂停 CPLEX 并为其提供解决方案?
- angular - 将方法传递给子组件
- c# - MRTK (V2) 需要更新 Hololens?
- python - 填充奇怪的行为,当有重复的列名时