读取cvs文件并存储在缓冲区时出现问题

时间:2016-09-03 18:13:00

标签: c string file csv io

我有一个csvdouble值的文件(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");
    }

}

感谢任何帮助。

2 个答案:

答案 0 :(得分:1)

  1. 您正在将token类型转换为(char)token是一个字符指针 - 基本上是指向包含下一个,分隔标记的字符串的指针。您需要将该字符串中包含的浮点数解析为double值,而不是将字符串指针本身强制转换为char值。请尝试sscanf()
  2. 输出值时,您输出的是最后一个输入缓冲区中的字符,而不是您(尝试)从输入中解析的双精度值。将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

注意:

  1. 使用atof()中从字符串解析为double。
  2. 我们通常更喜欢fgets() over getc()