我如何阅读此文本文件中的城市名称和坐标?

时间:2013-07-27 22:56:55

标签: c file io distance

我正在尝试制作一个程序来计算地球上两点之间的距离以及方位角。然后,一旦我得到距离和方位角,我将不得不创建一个图形数据结构,它将使用Dijkstra的算法来找到最短的路径。

以下是文本文件中的几行。每一行代表两个城市位置的坐标,它们将找到两者之间的距离:

Cairo=  30:2:39 N 31:14:8 E |Cape Town=  33:55:29 S 18:25:26 E
Cape Town=  33:55:29 S 18:25:26 E |Cairo=  30:2:39 N 31:14:8 E
Cairo=  30:2:39 N 31:14:8 E |Lagos=  6:27:11 N 3:23:45 E
Lagos=  6:27:11 N 3:23:45 E |Cairo=  30:2:39 N 31:14:8 E
Lagos=  6:27:11 N 3:23:45 E |Cape Town=  33:55:29 S 18:25:26 E
Cape Town=  33:55:29 S 18:25:26 E |Lagos=  6:27:11 N 3:23:45 E
Lagos=  6:27:11 N 3:23:45 E |Birmingham=  52:20:10 N 1:53:25 E
Birmingham=  52:20:10 N 1:53:25 E |Lagos=  6:27:11 N 3:23:45 E

格式为:

<lat> d:m:s <N|S>, 
where d = degrees, m = minutes, s = seconds (max(d) == 90)
<lon> is d:m:s <E|W> (max(d) == 180)

分钟和秒钟重要吗?

这是我使用本网站http://www.krysstal.com/sphertrig.html上的余弦规则的距离函数:

void findDistance(float x1, float y1, float x2, float y2) {
    float a,b,c;
    float distance;

    /*

    if (latDir == 'W' or lonDir == 'S') {
        //change to negative
    }

    */

    a = y2-y1;
    b = 90-x1;
    c = 90-x2;

    printf("\na = %f b = %f c = %f",a,b,c); 

    //convert to radians for trig functions
    a = a * DEG_TO_RAD;
    b = b * DEG_TO_RAD;
    c = c * DEG_TO_RAD;

    printf("\na = %f b = %f c = %f",a,b,c); 

    distance = cos(b)*cos(c)+sin(b)*sin(c)*cos(a);

    printf("\nCos(distance) in radians = %f",distance);

    distance = acos(distance); 

    float distDegree = distance*RAD_TO_DEG;

    printf("\nCos(distance) in degrees = %f",distDegree);

    distance = EARTH_CIRCUM * distDegree/360;

    printf("\ndistance = %f",distance);

    //return distance; 



}

1 个答案:

答案 0 :(得分:1)

我冒昧地清理你的输入并将每个条目放在一行上,如下所示:

Birmingham=  52:20:10 N 1:53:25 E 
Cairo=  30:2:39 N 31:14:8 E 
Cape Town=  33:55:29 S 18:25:26 E
Lagos=  6:27:11 N 3:23:45 E

我也删除了重复项。

#include <stdio.h>

int  main() {
    char line[256];

    // data
    char name[64];
    // hour, minute, second, direction
    int lat_h, lat_m, lat_s; char lat_d;
    int long_h, long_m, long_s; char long_d;

    FILE *fin = fopen("in", "r");

    while (NULL != fgets(line, 256, fin)) {
        sscanf(line, "%[^=]=%*[ ]%d:%d:%d%*[ ]%c%*[ ]%d:%d:%d%*[ ]%c",
            name,
            &lat_h, &lat_m, &lat_s, &lat_d,
            &long_h, &long_m, &long_s, &long_d
        );

        printf("Name: %s\nlat: %d:%d:%d %c\nlong: %d:%d:%d %c\n\n",
            name, 
            lat_h, lat_m, lat_s, lat_d,
            long_h, long_m, long_s, long_d
        );

    }
    return 0;
}

如果您在一行中有多个条目,请按分隔符拆分并在每一行上执行sscanf

注意:此答案假设标题是您的实际问题。如果您的问题是Is the minutes and seconds important?,请阅读@ Jongware的评论。