我编写了下面的代码来从文本文件中读取数据并将值存储在数组中。我的代码没有读取文件。
正在使用的库头
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <math.h>
#include <conio.h>
我的主要
int main()
{
FILE *fpoo;
float NumArr[5];
//我同样试过“c:\Fly_u.txt”
fpoo= fopen ("Fly_u.txt","r");
if(fpoo!=NULL)
for (int i=0;i<6;i++)
{
fscanf(fpoo,"%d\n",NumArr[i]);
{
else
{
printf("me");
}
for (int i=0;i<6;i++)
{
printf("%f",NumArr[i]);
}
fclose(fpoo);
_getche();
return 0;
}
//文本文件内容如下
0.99247
0.14727
-0.00041387
-1.737
0.20475
-0.052151
0.14755
-0.0233
-0.32606
0.092085
0.059199
-0.025587
0.0097565
0.13639
0.12007
最佳答案
fscanf()
的使用不正确:
- 您需要为
float
使用格式说明符这是%f
, 不是int
- 你需要传递一个
float
的地址(即float*
),而不是float
改变:
fscanf(fpoo,"%d\n",NumArr[i]);
到:
fscanf(fpoo,"%f\n", &NumArr[i]);
fscanf()
返回成功分配的数量,在本例中应为 1
.建议在稍后尝试使用之前检查输入是否已成功读取。
如果指定 "Fly_u.txt"
作为文件名,那么它必须与进程的工作目录位于同一目录中。记得转义'\'
在构建路径时,或者只使用 '/'
(也适用于 Windows)。
for
循环将导致未定义的行为,因为数组索引从 0
运行至 N - 1
.所以对于 float NumArr[5];
有效索引是 0, 1, 2, 3, 4
但是 for
上的终止条件循环是 i < 6
使用 5
的索引: 非法的。要么增加 NumArr
的大小或调整 for
上的终止条件循环。
关于c++ - 用C中的文本文件的内容初始化一个数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11917792/