读取发生变化但该行的结构已知的文件行
我有一个逐行组织的文件,所有行的结构都是由我定义的,但每行的内容可以根据同一行包含的两个变量增加或减少。
行示例: 1 Andre 2 0 5 13 05 2011 4 13 05 2011
'1' 代表用户 ID
相关联的名称
'Andre' 代表与 ID '2 0' 细分: '2' 代表如何细分用户带回家的电影数量和“0”表示用户预订了多少部电影。
到目前为止,该行遵循模式 %d %s %d %d,它们可以存储在我想要的变量中。
现在最困难的部分来了。根据“2 0”部分,程序知道必须读取模式 %d %d %d %d(“5 13 05 2011”和“4 13 05 2011” - 代表带回家的电影日期)2 次而且程序还知道,在读取前一个模式的两倍后,它知道由于“2 0”中的零部分,我不需要读取任何其他内容。
包含更多数据的行示例: 1 Andre 2 1 5 13 05 2011 4 13 05 2011 7 14 05 2011
'2 1'
“2”部分告诉程序在该行中应该读取“ 5 13 05 2011'和'4 13 05 2011'到variable_one[i][4](示例)
'1'部分告诉程序在该行中应该读取'7 14 05 2011'到variable_two[i][ 4](示例)
我正在使用 fscanf(file, "%d %s %d %d", &id[i],&nomes[i],&livros_num[i][0] ,&livros_num[i][1]);
读取 '1 Andre 2 0' 但我如何根据 '2 0' 读取该行的其余部分?
I have a file that is organized line by line and the structure of all lines was defined by me but the contents of each line can increase or decrease according to two variables that the same line contains.
Line Example: 1 Andre 2 0 5 13 05 2011 4 13 05 2011
'1' represents the user ID
'Andre' represents the name associated to the ID
'2 0' subdivides: '2' represents how many movies the user as taken home AND '0' represents how many movies reservations the user has.
So far the line is following the pattern %d %s %d %d and they can be stored in the variables I want.
Now the hard part comes. Depending on the '2 0' part, the program knows that has to read the pattern %d %d %d %d ('5 13 05 2011' and '4 13 05 2011' - represent dates of movies taken home) 2 times and also the program knows that after reading 2 times the previous pattern it knows that i doesn't need to read anything else due to the zero part in '2 0'.
Example of line with more data: 1 Andre 2 1 5 13 05 2011 4 13 05 2011 7 14 05 2011
'2 1'
The '2' part tells the program that in that line it should read '5 13 05 2011' and '4 13 05 2011' to variable_one[i][4] (example)
The '1' part tells the program that in that line it should read '7 14 05 2011' to variable_two[i][4] (example)
I'm using fscanf(file, "%d %s %d %d", &id[i],&nomes[i],&livros_num[i][0],&livros_num[i][1]);
to read '1 Andre 2 0' but how can i read the rest of the line according to '2 0'?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
您可以使用fscanf。
这是一个例子:
You can use fscanf.
Here's an example:
第一次调用 fscanf 后,您需要根据读取的变量进行循环。您似乎已经意识到,您在第一次调用中读取的
int
决定了您在该行中需要的额外读取次数。After your first call of fscanf, you need to loop depending on the variables you read. You seem to have already realized that the
int
's you read in your first call determine the number of extra reads you need in the line.好吧,当您读取“2 0”时,您会得到两条信息:您需要循环查看带回家的电影日期的次数以及您需要循环读取所有预订的次数。
Well, when you read the '2 0' you get two pieces of information: the number times you need to loop for the dates of the movies taken home and the number of times you need to loop to read all the reservations.
怎么样
等等.
How about
etc.