【发布时间】:2016-10-01 04:52:46
【问题描述】:
我的 csv 文件包含以下内容:
BP BCS DEB EG GY KAP KEC MI
BP 0 216 511 311 22 23 242 550
Bekescsaba 216 0 23 34 11 345 23 42
Debrecen 511 642 0 124 31 124 123 315
Eger 311 1351 31 0 342 532 211 134
Gyor 22 135 341 431 0 134 23 312
Kaposvar 23 14 24 341 14 0 15 32
Kecskemet 242 241 241 135 14 15 0 231
Miskolc 550 24 4 12 352 124 123 0
我想将数字读入一个数组。问题是,我怎样才能做到这一点,同时也跳过第一个字符串?
这是读取所有内容的代码:
#include <stdio.h>
#include <stdlib.h>
#include <locale.h>
#include <math.h>
#include <time.h>
#define MAX 1024
void main() {
FILE *f;
float r;
int i, j;
char line[1024];
char city[MAX];
int mtx[20][20];
int szam[50];
char *cities[9] = {"Budapest", "Bekescsaba", "Debrecen", "Eger", "Gyor", "Kaposvar", "Kecskemet", "Miskolc"};
f = fopen("/home/dumika/Desktop/asd.csv", "r");
if(!f) printf("File opening problem!");
//fgets(line, 1024, f);
while(fscanf(f, "%s", city) != EOF)
{
printf("%s \n", city);
}
}
关于如何在 C 上实际管理 csv i/o 的信息很少。实际任务是要求用户输入两个城市,并计算距离。 我要做的是读取矩阵中的数字,并在指针数组中包含城市。用户写入,例如布达佩斯(索引 0)和埃格尔(索引 3),距离将为 311。(mtx[0][3]) 但我无法将数字读入二维数组。最好的方法是什么?
【问题讨论】:
-
但是文件不是逗号分隔的?
-
将事物读取为字符串,split them,它们使用函数将数字转换为整数或双精度数
-
旁白:请改进您的错误捕获:
printf("File opening problem!");在出现段错误之前可能不会出现在控制台上。在消息末尾添加\n,并在main中添加return 1。 -
问为什么凯奇凯梅特到米什科尔茨的距离是231,而米什科尔茨到凯奇凯梅特的距离是123,我是不是很挑剔?数据中还有许多其他此类异常。同样如评论所述,它不是 CSV 文件。如果是这样,它可以处理多个单词的城市名称,但现在它不能。也许它是一个 TSV(制表符分隔值)文件。
标签: c