2016-09-28 5 views
-3

浮動小数点csvをcの2次元配列に変換する必要があります。整数配列への変換を説明している記事(Import CSV elements into a 2D array in C)を見たことがあります。このコードを変更する際の助けや、csvを浮動小数点2D配列に変換するための新しいアプローチを使用できます
例:my csv 0.018869,0.015863,0.044758,0.027318,0.049394,0.040823、.....のような値を含み、4400 * 500値のCSVです。だから、これらの値をすべて含めるには、サイズ4400 * 500の大きな配列を使用する必要があります。事前浮動小数点csvをcの2d配列に変換する

+0

上に読みたい場合は、我々はあなたがそれを修正することができますように問題を試み、解決しなければならないコードを含めてくださいリンクです。あなたの質問を編集しても問題ありません。 –

答えて

0

atof()を使用して文字列を浮動体に変換します。 Hereは、あなたがそれ

#include <stdio.h> 
#include <stdlib.h> 
#include <string.h> 

//counters 
int i = 0; 
int j = 0; 
int k = 0; 

char c = 0; //for storing a char at a time 

char result_char_array[4] = {0}; //float is a 32 bit number, so 4 bytes 

FILE *filep; //pointer to file structure 

float results[100] = {0}; //to store the float 

int main(void) 
{ 

    filep = fopen("C:/Documents/test.csv", "r");  //open file , read only 
    if (!filep) 
    { 
     fprintf (stderr, "failed to open file for reading\n"); 
     return -1; //return negative number so you know something went wrong 
    } 

    c = fgetc(filep); //get first character 

    while(c != EOF) 
    { 
     if((c == ',') || (c == '\n')) //we want to stop at each comma or newline 
     { 
      //i = 0; //reset the count 
      results[j] = atof(result_char_array); //this converts a string to a float 
      j++; //increment j 
      memset(&result_char_array, 0, sizeof(result_char_array)); //clear the array 
     } 
     else 
     { 
      strncat(&result_char_array, &c, 1); 
     } 


     c = fgetc(filep); //get next character 
     i++; 
    } 

    results[j] = atof(result_char_array); //convert last number 

    fclose (filep); //always close the file 

    for(k = 0; k <= j; k++) 
    { 
     printf("Number %d is: %f\n",k, results[k]); //loop through the results and print line by line 
    } 
    getchar(); 
    return 1; 
} 
+0

ハハはi = 0をコメントアウトして無視しています –

0

おかげで、ANSI C89で書かれたCSVライブラリですlibcsvを見て、ください。しかし、libcs​​vはLGPLの下でライセンスされているので注意してください。

関連する問題