如何把一个.csv的文件导入到C++的一个实型数组中?

.csv中的数据是用逗号隔开的实数,如何导入C++的一个数组中,保证可以作为float的数组引用

#include<cstdio>
#include<cstdlib>
using namespace std;

const int MAX = 100;

int num[MAX];//数组类型自定
int main(){
FILE *file = fopen("" , "r");//第一个参数传入你的路径,也即"路径/*.csv"
int i = 0;
while(fscanf(file , "%d" , num[i]) != EOF){
i++;
}
}

C++语法,但是基本用C来写的,可自行改成C

温馨提示:答案为网友推荐,仅供参考
第1个回答  2014-05-31
#include <iostream>
#include <fstream>
using namespace std ;

void out( float *a, int n )
{
     int i;
     for( i=0;i<n;i++ )
          cout << a[i] << " " ;
     cout << endl ;
}

int main()
{
    float array[1024]; //不够,可以自己增加
    int i;
    char ch;
    ifstream infile ;
    infile.open( "text.txt" ); //当前目录下
    if ( !infile.good() )
    {
        cout << "open file error" <<endl;
        system("pause");
        return -1;        
    } 
    i=0;
    while( !infile.eof() )
    {
        infile >> array[i++];

        if ( infile.fail() )
        {
            i--;
            break;
        }
        infile >> ch ;
        if ( infile.fail() )
        {
            break;
        }
    }
    infile.close();
    out( array, i ); //显示数组内容
    system("pause");
    return 0;
}

本回答被提问者采纳
第2个回答  2014-05-31
#include <stdio.h>

float data[10][3];  //10行数据,每行3列

int main()
{
    int line=0;
    FILE file=fopen("file.dat","r");
    while(!feof(file))
    {
        fscanf("%f,%f,%f", &data[line][0], &data[line][1], &data[line][2]);
        line++;
    }
    fclose(file);
}

相似回答