【发布时间】:2022-01-24 05:46:26
【问题描述】:
我有一个 csv 文件,其中包含用逗号分隔的数字,每个数字都像 1,2,3,4,5,6,7,8,9....。我打算将所有这些数字解析为我用 c 编程语言初始化的向量,我已经设法使用下面的代码将文件中的所有字符读取到文件末尾,我现在的问题是分配字符使用getc() 函数将其提取到字符串中,以进行基于逗号的进一步处理,在此我将使用逗号作为分隔符变量将字符串拆分为字符串数组。我尝试在每次迭代时将字符分配给字符串,但没有成功,请帮助
#include <string.h>
#include <stdio.h>
int main() {
// define the vector file
FILE* vec = fopen("vectors.csv", "r");
// define the dimensions of the vector
int rows = 100;
// this vector has 100 rows for instance
int vec[rows];
//I managed to read the csv file now I need to read it into a string
char ch,line;
while((ch=getc(vec))!=EOF){
//append the characters to the empty string
line+=ch;
}
//confirm the accuracy of the string by outputting it
printf("%s",line);
//the above line outputs blank, please help
return 0;
}
我一直认为向量与一维数组相同,但我的研究可能会让我误入歧途,请帮助。
【问题讨论】:
-
有理由不使用
fscanf()吗?您是否有任何需要担心的空白字段(相邻的逗号)? -
不,它们不是空的相邻逗号。每个逗号后面都有一个数字
-
我如何使用 fscanf 来做到这一点?
-
所以,用
fscanf()一次读一个数字。%d后面可以加逗号;你不会知道什么时候不匹配,但也没关系。 -
我使用循环然后使用
fscanf()分配?它返回一个整数吗?