我有一个包含数字的文本文件:每行两个数字,用空格分隔。每对数字代表一个 (x, y) 坐标。我正在尝试用 C 语言编写此代码,因为这是我所知道的语言,但我正在 Visual Studio 2010 中工作。我的代码如下:
#include "stdafx.h"
#include <stdio.h>
#include <stdlib.h>
#define MAXPOINTS 10
int _tmain(int argc, _TCHAR* argv[])
{
double points [MAXPOINTS];
int i;
for (i = 0; i < MAXPOINTS; i++) {
points[i] = 0.0;
}
FILE* pFile;
pFile = fopen ("points.txt","r");
if (pFile == NULL)
{
printf("Could not open file\n");
return 0;
}
rewind (pFile);
i = 0;
while (fscanf(pFile, "%f %f", &points[i], &points[i + 1]) == 2) {
printf("blah\n");
i = i + 2;
}
for (i = 0; i < MAXPOINTS; i++) {
printf("[%d] = %f\n", i, points[i]);
}
fclose (pFile);
return 0;
}
输出为:
blah
blah
blah
[0] = 0.000000
[1] = 0.000000
[2] = 0.000000
[3] = 0.000000
[4] = 0.000000
[5] = 0.000000
[6] = 0.000000
[7] = 0.000000
[8] = 0.000000
[9] = 0.000000
其中points.txt有三行:
100 200
300 400
500 500
我不明白为什么这些数字没有被读入数组。
有什么想法吗?
最佳答案
%f 格式要求指针为浮点型,而您将指针指定为 double 型。
关于c - 从文本文件中读取 double (使用 C/Visual Studio),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6584605/