[英]How to read in both Strings and Ints from a file, on seperate lines
so I have been searching your website and im still very unclear on how to do this, so let me try to explain this as best I can. 因此,我一直在搜索您的网站,但我仍然不清楚如何执行此操作,因此,我将尽我所能解释。
I have a input file like so: 我有一个像这样的输入文件:
2
Joe Flacco
1 3 5 6 7 8
Tom Brady
7 9 10 15 52 53
The first number is the number of "people" in the file, and the next is their first and last name. 第一个数字是文件中“人员”的数目,第二个是他们的名字和姓氏。 Next is 6 ints between [0,53] that are their "lottery" numbers.
接下来是[0,53]之间的6个整数,它们是它们的“彩票”数字。 Anyways, I can get my code to pull in the first number, but getting theirs names and numbers is proving hard.
无论如何,我可以让我的代码输入第一个数字,但是事实证明,获取他们的姓名和数字非常困难。
The last part, is getting it to fit in the struct we have declared (which we must use, that contains variables firstName[20] lastName[20] and numbers[6]. I know I am way off on how to do this all properly, but I am posting my code so you guys can see what Im doing. I appreicate any and all help. Also, Im trying to learn how to do it, not get you to right a program for me, so any explanations are very welcome. 最后一部分是使其适应我们声明的结构(我们必须使用该结构,该结构包含变量firstName [20] lastName [20]和数字[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);
}
Using fgets
strtok
and atoi
will give you what you need. 使用
fgets
strtok
和atoi
将为您提供所需的东西。 As for your program's structure, you probably want something like this: 至于程序的结构,您可能想要这样的东西:
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();
}
you can use fgets() function for this purpose. 您可以为此使用fgets()函数。 it will read lines as String.
它会将行读为String。 after reading the numeric as string, just convert it to integer.
将数字读取为字符串后,只需将其转换为整数即可。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.