[英]Reading multiple text files into an array in C
I am writing a program that opens numerous text files and reads from them parameters for planetary bodies. 我正在编写一个程序,该程序打开许多文本文件并从中读取行星体的参数。 I have a problem when reading the text files.
读取文本文件时出现问题。
sample text file 样本文本文件
2
1, 1, 2
3.5, 3, 4
The first number (2) refers to the number of bodies found in the file. 第一个数字(2)表示在文件中找到的实体的数量。 The next 2 lines correspond to the planet's parameters (x and y coordinates and mass respectively).
接下来的两行对应于行星的参数(分别为x和y坐标和质量)。 I have 4 text files containing different amounts of bodies and need to store all the data in a variable.
我有4个文本文件,其中包含不同数量的主体,并且需要将所有数据存储在变量中。
my code 我的密码
struct body {
float x;
float y;
float mass;
};
int main()
{
struct body b[8];
FILE *fp;
int i, j, k;
int num, count = 0;
char fName[10];
for (i = 1; i < 5; i++)
{
sprintf(fName,"bodies%d.txt",i);
fp = fopen(fName, "r");
if (fp == NULL)
{
printf("Can't open %s \n",fName);
exit(-1);
}
fscanf(fp, "%d", &num);
for (j = count; j < num; j++)
{
fscanf(fp, "%f%*c %f%*c %f%*c", &b[j].x, &b[j].y, &b[j].mass);
printf("%f %f %f\n", b[j].x, b[j].y, b[j].mass);
count = j;
}
}
It is reading the numbers from the text files, but it is stopping after 6 readings and there are 8 in total. 它正在从文本文件中读取数字,但在6次读取后停止,总共有8次。
What could be the problem? 可能是什么问题呢?
尝试在第二个for
循环中用j = 0
替换j = count
。
Your code has some problems : 您的代码有一些问题 :
fName
is declared as fName
被声明为
char fName[10];
and you use 而你用
sprintf(fName,"bodies%d.txt",i);
which writes 12 characters into fName
(including the NUL-terminator) which can atmost hold 9 characters(+1 for the NUL-terminator). 它会将12个字符写入
fName
(包括NUL终止符)中,最多可容纳9个字符(NUL终止符为+1)。
The for
loop: for
循环:
for (j = count; j < num; j++) { fscanf(fp, "%f%*c %f%*c %f%*c", &b[j].x, &b[j].y, &b[j].mass); printf("%f %f %f\\n", b[j].x, b[j].y, b[j].mass); count = j; }
has many problems and is confusing too. 有很多问题,也令人困惑。 When you do
j = count
, you check j < num
. 当您执行
j = count
,请检查j < num
。 This makes no sense as count
is not related to num
. 这是没有意义的,因为
count
与num
不相关。
Fixes : 修正 :
For the first problem, allocate enough space for fName
: 对于第一个问题,为
fName
分配足够的空间:
char fName[12];
instead of 代替
char fName[10];
As for the second problem, use 至于第二个问题,使用
for (j = 0; j < num; j++) //j should be initialized to 0 { fscanf(fp, "%f%*c %f%*c %f%*c", &b[count].x, &b[count].y, &b[count].mass); printf("%f %f %f\\n", b[count].x, b[count].y, b[count].mass); //Use b[count] instead of b[j] //count = j; Works, but the below is better count++; }
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.