gpt4 book ai didi

c - 在 C 中使用 fscanf

转载 作者:太空宇宙 更新时间:2023-11-04 06:33:41 25 4
gpt4 key购买 nike

我正在尝试从文件中读入数组。我的名为 Players.txt 的文件包含:

Del Piero|3|Italy|Juventus|
Ronaldo|0|Portugal|Real Madrit

我使用了 fscanf ,但它没有正常工作,我没有做正确的转换。

谁能帮我读取它们并将它们存储到数组中。比如数组球员名字要包含{ Del Piero, Ronaldo}

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

#define NUM_PLAYERS 20
#define NAME_LENGTH 100
#define COUNTRY_NAME 20

int main (void)

{
FILE *Players;

char player_name [NUM_PLAYERS][NAME_LENGTH] = {0};
char country_name[NUM_PLAYERS][COUNTRY_NAME] = {0};
char team_name[NUM_PLAYERS][NAME_LENGTH] = {0};
int goals_scored[NUM_PLAYERS] = {0};
int i;

Players = fopen("G:\\COP2220\\Project 5\\Players.txt", "r");
if (Players == NULL)
{
printf("File not found.\n");
}
else

{

while (fscanf(Players, " %[^|]s %[^|]d %[^|]s %[^|]s",player_name[i],&goals_scored[i],country_name[i],team_name[i]))
{
printf("The player %s, scored %d from %s plays in %s\n", player_name, goals_scored,country_name, team_name );
}
}

fclose(Players);
return 0;
}

最佳答案

[] 本身就是一个类型,您不应该在它的结束。您真正需要做的就是将格式更改为:

"%[^|] | %d | %[^|] | %[^|]|\n"

并考虑更改您的 while 循环以在 fscanf 不返回 4 时中断。

这是一些工作代码:

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

#define NUM_PLAYERS 20
#define NAME_LENGTH 100
#define COUNTRY_NAME 20

int
main (void)
{
FILE * Players;
char player_name [NUM_PLAYERS][NAME_LENGTH] = {0};
char country_name[NUM_PLAYERS][COUNTRY_NAME] = {0};
char team_name[NUM_PLAYERS][NAME_LENGTH] = {0};
int goals_scored[NUM_PLAYERS] = {0};
int i = 0, ret = 0;

Players = fopen("testfile", "r");

if (Players == NULL)
{
printf("File not found.\n");
}

else
{
for (;;)
{
ret = fscanf(Players, "%[^|] | %d | %[^|] | %[^|]|\n",
player_name[i],
&goals_scored[i],
country_name[i],
team_name[i]);

if (ret != 4)
{
printf ("only %d arguments were matched\n", ret);
break;
}

printf("The player %s, scored %d from %s plays in %s\n",
player_name[i],
goals_scored[i],
country_name[i],
team_name[i]);
i++;
}
fclose(Players);
}
return 0;
}

关于c - 在 C 中使用 fscanf,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17561495/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com