读取空间将 C 中的浮点值逐行分隔



我接到了一个任务,从 C 语言中的数据.txt文件中读取空格分隔的浮点值。

文件看起来像这样...

0.329412 0.800000 0.800000 0.290196
0.329412 0.800000 0.800000 0.290196 
0.329412 0.800000 0.800000 0.290196
0.329412 0.800000 0.800000 0.290196 
0.796078 0.800000 0.800000 0.796078 
0.796078 0.800000 0.800000 0.796078 
0.796078 0.800000 0.800000 0.796078 
0.796078 0.800000 0.800000 0.796078 
0.796078 0.800000 0.800000 0.796078 
0.796078 0.800000 0.800000 0.796078 
0.329412 0.800000 0.800000 0.290196 
0.329412 0.800000 0.800000 0.290196 
0.329412 0.800000 0.800000 0.290196 
0.329412 0.800000 0.800000 0.290196 
0.329412 0.800000 0.800000 0.290196 

中间两行是常量。任务是查找第 1 行和第 4 行何时都在 0.7 或更高的范围内 并记下它。这只是文件的一个片段,但在这里它们会在一段时间内超过 0.7,因此计数增加 由一个。实际文件有数千行,但只有四列。

我试过这样的:

#include<stdio.h>
#include<stdlib.h>
int main()
{
float arr[4000][4];
int i, j, vals =0, count = 0;
FILE *fpointer;
char filename[10];
printf("Enter the name of the file to be read: ");
scanf("%s",filename);
fpointer = fopen(filename, "r");
if (fpointer == NULL)
{
printf("Cannot open file n");
exit(1);
}
while(!feof(fpointer))
{
for(i=0; i<4000; i++)
{
for(j=0; j<4; j++)
{
fscanf(fpointer, " %f ", &arr[i][j]);
}
if (arr[i][0] >= 0.7 && arr[i][3] >= 0.7)
vals += 1;
else if (arr[i-1][0] >= 0.7 && arr[i-1][3] >= 0.7)
count += 1;
}
}
printf("number of counts: %d", count);
fclose(fpointer);
}

但是我被告知要逐行读取文件,然后进行评估,而不是存储到一个大数组中,因为程序可能会崩溃 如果是大文件。

你能帮我这样做吗?我有类似的大文件,我不确定它们有多少行。

请让我知道如何逐行读取值并同时对其进行评估。

提前谢谢你。

看看为什么"while ( !feof (file(("总是错的?

相反,在fscanf给出有效结果时循环,并且由于中心列是常量的,您可以使用%*f说明符跳过它们:

#include <stdio.h>
#include <stdlib.h>
int main(void)
{
// char filename[9];
char filename[128]; // Don't be stingy, use more RAM :)
FILE *fpointer;
printf("Enter the name of the file to be read: ");
scanf("%127s", filename);
fpointer = fopen(filename, "r");
if (fpointer == NULL)
{
printf("Cannot open file n");
exit(EXIT_FAILURE);
}
int count = 0;
float arr[2];
while (fscanf(fpointer, "%f %*f %*f %f", &arr[0], &arr[1]) == 2)
{
if ((arr[0] >= 0.7) && (arr[1] >= 0.7))
{
count++;
}
}
printf("number of counts: %dn", count);
fclose(fpointer);
return 0;
}

使用fgetssscanf更安全的版本(如@DavidC.Rankin在评论中指出的那样(:

int count = 0;
char str[256];
float arr[2];
while (fgets(str, sizeof str, fpointer) != NULL)
{
sscanf(str, "%f %*f %*f %f", &arr[0], &arr[1]);
if ((arr[0] >= 0.7) && (arr[1] >= 0.7))
{
count++;
}
}

最新更新