所以我一直在搜索你的网站,但我仍然很不清楚如何做到这一点,所以让我尽力解释一下。
我有一个像这样的输入文件:
2
Joe Flacco
1 3 5 6 7 8
Tom Brady
7 9 10 15 52 53
第一个数字是文件中“人员”的数量,第二个数字是他们的名字和姓氏。接下来是 [0,53] 之间的 6 个整数,它们是他们的“彩票”号码。无论如何,我可以让我的代码提取第一个数字,但事实证明获取他们的姓名和数字很难。
最后一部分是让它适合我们声明的结构(我们必须使用它,其中包含变量firstName[20]lastName[20]和numbers[6]。我知道我在如何正确地完成这一切,但我发布我的代码,以便你们可以看到我在做什么。我感谢所有的帮助。另外,我试图学习如何做到这一点,而不是让你们为我正确的程序,所以任何非常欢迎解释。
for(int i=0; i < numPlays;i++)
{
char firstName[20];
char lastName[20];
for(int x=0; x<3;x++)
fscanf(fr, "%c", &firstName[x]);
for(int x=0; x<6;x++)
fscanf(fr, "%c", lastName[x]);
for(int g=0; g<6; g++)
{
fscanf(fr, "%d", &Steve.numbers[g]);
}
temp[i]= Steve;
//Tester code, lets hope this works
for(int x=0; x<3;x++)
printf("The persons name is %c.\n",&firstName[x]);
//printf("The persons last name is %c.\n",temp[i].lastName);
}
最佳答案
使用fgets
strtok
和atoi
将为您提供您所需要的。至于你的程序结构,你可能想要这样的东西:
typedef struct Player {
char name[20];
int numbers[6];
} Player;
#define SIZE(x) (sizeof(x)/sizeof(*(x)))
Player readplayer(){
Player p;
int x;
char * num;
//read a line with fgets;
//memcpy() to p.name;
//read another line
for(num=strtok(line, " "),x=0;x<SIZE(p.numbers);x++, num=strtok(NULL," "))
p.numbers[x] = atoi(num);
return p;
}
int main()
{
//read a line with fgets
int x, nplayers = atoi(line);
Player *players = malloc(nplayers*sizeof(Player));
for(x=0;x<nplayers;x++)
players[x] = readplayer();
}
关于c - 如何从文件中的不同行读取字符串和整数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8967320/