arrays - 如何从文件C创建一个int字符串
问题描述
我有一个file.csv
包含一对用逗号分隔的 int 。我的目标是从文件 ( fgets
) 中读取数字并将它们char (*arr)
像字符串一样放入。问题是它在逗号后添加了更多数字。我能怎么做?
例如这个号码:9514902,846 在arr:9514902,845962
主程序
#define SIZE 10
#define LEN 20
int main(){
char (*arr)[LEN] = NULL;
int pos = 0;
FILE *fd = NULL;
fd = fopen("file.csv", "r");
arr = calloc ( SIZE, sizeof *arr);
while ( pos < SIZE && fgets ( arr[pos], sizeof arr[pos], fd)) {
printf ("%s", arr[pos]);
++pos;
}
fclose ( fd);
free ( arr);
return 0;
}
文件.csv
9514902,846
1134289,572
7070279,994
30886,48552
750704,1169
1385812,729
471548,3595
8908491,196
4915590,362
375309,212
我的输出:
9514902,845962
1134289,571587
7070279,993574
30886,485520
750704,116888
1385812,729300
471548,359462
8908491,19559
4915590,361558
375309,211958
解决方案
您可以使您的代码更易于编写、维护和理解。如我所见,您也不需要动态内存分配。
改成
#define SIZE 10
#define LEN 20
int main(){
char arr[LEN] = {0}; // just define a char array, should be sufficient.
int pos = 0;
FILE *fd = NULL;
fd = fopen("file.csv", "r");
if (!fd) { // don't for get the error check
printf ("File handling error\n");
exit (-1);
}
while ( pos < SIZE && fgets ( arr[pos], LEN, fd)) {
printf ("%s", arr[pos]);
++pos;
}
fclose ( fd);
}
推荐阅读
- php-5.6 - 具有未知长度的数组的偏移量
- mysql - sql插入时如何抑制唯一键检查
- javascript - 如何将Javascript变量传递给PHP函数
- git - 使用 gerrit/git 命令行检测 gerrit 补丁是否需要变基?
- javascript - 如何测试一个点是否在 SVG 封闭路径内
- php - 如何插入两个表的 ID(多对多关系)
- angular - “ngbd-modal-component”不是已知元素
- hibernate - Hibernate Search - recreate index if existing data was not indexed before
- excel - VBA中两个日期之间的间隔
- java - 在 Hyperledger Fabric 上创建通道时,由于超时发送事务失败