2016-09-03 97 views
-1

我有一個csv文件double值(20行和4列),我想要讀取和存儲在緩衝區中的值來執行一些操作。我的下面的實現給了我一些屏幕上的字符。我試圖看看問題出在哪裏,但我不知道在哪裏:當讀取CVS文件並存儲在緩衝區時問題

#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

這不是如何讀取CSV中的「double」值(應該是純文本)到'double'緩衝區中。 – usr2564301

+0

要走的路是使用'fgets'的返回值來控制循環。就目前而言,您在查明輸入是否有效之前會處理(錯誤地查看答案)輸入。慣用的方式是'while(fgets(buff,80,fp)!= NULL){...}'。然後你不需要用'getc'來瞎搞。 –

+0

您還應該在'strtok'分隔符或甚至'\ r \ n'中包含換行符'\ n'來覆蓋各種操作系統行尾。從你使用'getc'的方式來看,你似乎沒有意識到'fgets'保留了來自輸入的'newline'。這樣可以確定輸入行是否由於長度約束而中斷,在下一次調用'fgets'時繼續 - 這不會「忘記」輸入行的其餘部分。 –

回答

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()到 解析從字符串雙倍於
  2. 我們通常更喜歡fgets() over getc()
+1

感謝您的幫助和評論。我其實是一個C初學者 – Alli

1
  1. 您正在輸入token(char)token是一個字符指針 - 基本上,指向包含下一個, - 限制標記的字符串。您需要將該字符串中包含的浮點數解析爲double值,而不是將該字符串指針自身的類型轉換爲char值。試試sscanf()
  2. 當您輸出您的值時,您正在輸出最後一個輸入緩衝區中的字符,而不是您嘗試從輸入中解析出的雙值。更改您的printf命令以輸出雙精度值(例如,%f%g),並將您的buffer雙精度數組中的值傳遞給它,而不是buff字符數組。