c - 读取 csv 文件并存储在缓冲区中时出现问题

标签 c string file csv io

我有一个包含 double 值(20 行和 4 列)的 csv 文件,我想读取该文件并将这些值存储在缓冲区中以执行某些操作。我的以下实现在屏幕上显示了一些字符。我试图查看问题出在哪里,但我不知道问题出在哪里:

#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");
    }

}

感谢任何帮助。

最佳答案

不错的尝试,稍微修改一下,如下所示:

#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() .

关于c - 读取 csv 文件并存储在缓冲区中时出现问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39309993/

相关文章:

c - 从c中的文件中获取字符

c - 我如何 typedef struct <name> *var_name[32]

java - 我错过了什么? NumberFormatException 错误

python - 如何在读取 CSV 文件时将字符串值转换为整数值?

c# - 如何用WinRT打开打包后的文件

javascript - 过滤 Google 开发工具中“网络”选项卡中显示的文件

java - Android开发图片上传损坏

c - 用递归反转c中的字符串

创建特定的进程树

javascript - 从文本中删除文本和数字