我有一个csv
个double
值的文件(20行和4列)我想要读取并将值存储在缓冲区中以执行某些操作。我的以下实现在屏幕上给了我一些字符。我试着看看问题出在哪里,但我不知道在哪里:
#include<stdio.h>
#include <stdlib.h>
#include<String.h>
int main()
{
char buff[80];
double buffer[80];
char *token = NULL;
FILE *fp = fopen("dataset.csv","r");
if(fp == NULL){
printf("File Reading ERROR!");
exit(0);
}
int c = 0;
do
{
fgets(buff, 80, fp);
token = strtok(buff,",");
while( token != NULL )
{
buffer[c] = (char) token;
token = strtok(NULL,",");
c++;
}
}while((getc(fp))!=EOF);
for(int i=1; i<=80; ++i){
printf("%c ", buff[i]);
if(i%4 == 0) printf("\n");
}
}
感谢任何帮助。
答案 0 :(得分:1)
token
类型转换为(char)
。 token
是一个字符指针 - 基本上是指向包含下一个,
分隔标记的字符串的指针。您需要将该字符串中包含的浮点数解析为double
值,而不是将字符串指针本身强制转换为char
值。请尝试sscanf()
。printf
命令更改为输出双精度值(例如%f
或%g
)并将值传递给buffer
双精度数组,而不是buff
字符数组。答案 1 :(得分:1)
很好的尝试,稍微修改一下,像这样:
#include <stdio.h>
#include <stdlib.h>
#include <string.h> // not String.h
int main(void)
{
char buff[80];
double buffer[80] = {0}; // I like initialization my arrays. Could do for 'buff' too
char *token = NULL;
FILE *fp = fopen("dataset.csv","r");
if(fp == NULL){
printf("File Reading ERROR!");
exit(0);
}
int c = 0;
while(fgets(buff, 80, fp) != NULL) // do not use 'getc()' to control the loop, use 'fgets()'
{
// eat the trailing newline
buff[strlen(buff) - 1] = '\0';
token = strtok(buff, ",");
while( token != NULL )
{
// use 'atof()' to parse from string to double
buffer[c] = atof(token);
token = strtok(NULL,",");
c++;
}
}
// print as many numbers as you read, i.e. 'c' - 1
for(int i=1; i<=c - 1; ++i) // be consistent on where you place opening brackets!
{
printf("%f\n", buffer[i]);
}
// Usually, we return something at the end of main()
return 0;
}
示例运行:
C02QT2UBFVH6-lm:~ gsamaras$ cat dataset.csv
3.13,3.14,3.15,3.16
2.13,2.14,2.15,2.16
C02QT2UBFVH6-lm:~ gsamaras$ ./a.out
3.140000
3.150000
3.160000
2.130000
2.140000
2.150000
2.160000
注意: