我需要读取CSV表并将其值用于函数,但scanf()函数只读取文件的第一列。我还需要代码才能读取多个文件,而不允许我指定文件的名称。这样做的正确方式是什么?
示例:
CSV文件行:114 -0.44 -0.15385 -0.76293
代码输出:114 0.00 0.00 0.00
我的代码:
#include <stdio.h>
#include <tgmath.h>
#include <stdlib.h>
int main(){
long sec;
long wait = 0;
int fall = 0;
double x;
double y;
double z;
double mag = 0.0;
long i =0;
while(1){
scanf("%ld %lf %lf %lf", &sec, &x, &y, &z);
mag = sqrt(pow(x,2)+pow(y,2)+pow(z,2));
break;
}
printf("%ld %lf %lf %lf\n", sec, x, y, z);
output1(wait);
output2(fall);
return 0;
}发布于 2017-04-06 09:03:45
如果您在Windows上,您可以使用dirent.h并创建一个输入目录,您可以在其中存储输入文件。
一旦你有了文件,你就可以做一个适当的处理,并开始从其中读取行。因为您有一个csv文件,所以可以使用strtok将行拆分为标记,然后用它们加载变量。
发布于 2017-04-06 09:45:03
阻止您读取多个文件的是,您正在使用stdin读取数据,而不是打开所需的文件?如果您要重复做同一件事,但是使用不同的输入(即文件名),您应该创建一个函数,类似于.
void myfunc(char *filename)
{
FILE *thefile;
double x,y,z;
long sec;
thefile=fopen(filename,"r");
if(thefile)
{
if(fscanf(thefile,"%ld %lf %lf %lf", &sec, &x, &y, &z)==4)
{
/* do stuff */
}
fclose(thefile);
}
}然后,在主目录中,可以使用命令行参数来指定文件名如下
int main(int argc,char *argv[])
{
int i;
for(i=1;i<argc;i++)
{
myfunc(argv[i]);
}
}https://stackoverflow.com/questions/43250043
复制相似问题