2011-07-05 49 views
0

我有一個帶數字的文本文件:每行有兩個數字,用空格分隔。每對數字代表一個(x,y)座標。我想用C寫這篇文章,是因爲這是我知道的語言,但我在Visual Studio中工作2010年我的代碼如下:從文本文件(使用C/Visual Studio)讀入雙打

#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 

我想不通爲什麼這些數字沒有被讀入數組。

任何想法?

回答

2

%f格式需要指向浮點的指針,並且您將指針指向double。