我想用“fscanf”导入数字(总共 40000 个,以空格分隔)(格式:2.000000000000000000e+02)并将其放入一维数组中。我尝试了很多事情,但得到的数字很奇怪。
到目前为止我所拥有的:
int main() {
FILE* pixel = fopen("/Users/xy/sample.txt", "r");
float arr[40000];
fscanf(pixel,"%f", arr);
for(int i = 0; i<40000; i++)
printf("%f", arr[i]);
}
Run Code Online (Sandbox Code Playgroud)
我希望有人可以帮助我,我是初学者;-) 非常感谢!
代替:
fscanf(pixel,"%f", arr);
Run Code Online (Sandbox Code Playgroud)
这与此完全相同,并且只读取一个值:
fscanf(pixel,"%f", &arr[0]);
Run Code Online (Sandbox Code Playgroud)
你要这个:
for(int i = 0; i<40000; i++)
fscanf(pixel,"%f", &arr[i]);
Run Code Online (Sandbox Code Playgroud)
完整代码:
#include <stdio.h>
#include <stdlib.h>
int main() {
FILE* pixel = fopen("/Users/xy/sample.txt", "r");
if (pixel == NULL) // check if file could be opened
{
printf("Can't open file");
exit(1);
}
float arr[40000];
int nbofvaluesread = 0;
for(int i = 0; i < 40000; i++) // read 40000 values
{
if (fscanf(pixel,"%f", &arr[i]) != 1)
break; // stop loop if nothing could be read or because there
// are less than 40000 values in the file, or some
// other rubbish is in the file
nbofvaluesread++;
}
for(int i = 0; i < nbofvaluesread ; i++)
printf("%f", arr[i]);
fclose(pixel); // don't forget to close the file
}
Run Code Online (Sandbox Code Playgroud)
免责声明:这是未经测试的代码,但它应该让您了解您做错了什么。