【发布时间】:2012-01-23 04:52:07
【问题描述】:
所以我一直在搜索你的网站,但我仍然不清楚如何做到这一点,所以让我尽我所能解释一下。
我有一个像这样的输入文件:
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);
}
【问题讨论】:
-
对于初学者,您需要使用
"%s"来读取字符串,使用fscanf而不是逐个字符读取,即fscanf(fr, "%s", lastName);(注意没有&或@ 987654328@ & 没有for循环)。但使用fgets更安全。同样在printf打印字符使用"%c",但不要传递地址,即printf("The persons name is %c.\n",firstName[x]);或更好地直接打印字符串printf("The persons name is %s.\n",firstName);(不带for循环)。NULC 中 strings 的终止是必须的