C++读取csv文件求代码

我想用C++做数据分析 但是我的数据都是在excel里,我将其转化成了.csv文件,其中里面的数据使用逗号分隔,例如:
i,2,3
2,j,4
我想将这些数据放入一个二维的数组中,求C++代码
由于我的数据只有英文字母和整数,我不介意将字母用int格式保存

按你上面的数据例子,
假定你的格式是 3列,用2 个逗号分隔,
那么先按1行 3 个字符串 读入。
再用 sscanf 把字符串 转 整型。
转整型失败者不是数字,则赋值成 -999。
=================
#include <stdio.h>
FILE *fin;
char s1[20],s2[20],s3[20];

int main(){
int a[100][3]; //你要的2 维数组。
int i, n=0;
fin=fopen("abc.csv","r"); // 打开文件
while(1) {
fscanf(fin,"%[^,],%[^,],%s",s1,s2,s3); //关键的 有格式 读法
if (feof(fin)) break;
if ( sscanf(s1,"%d",&a[n][0])==0) a[n][0]= -999; //转换
if ( sscanf(s2,"%d",&a[n][1])==0) a[n][1]= -999;
if ( sscanf(s3,"%d",&a[n][2])==0) a[n][2]= -999;
n++; // 记录读入的行数
}
fclose(fin);
printf("n=%d\n",n);
for (i=0;i<n;i++) printf("%d %d %d\n",a[i][0],a[i][1],a[i][2]);
return 0;
}
温馨提示:答案为网友推荐,仅供参考
第1个回答  推荐于2018-03-26
#include "stdafx.h"

#include <iostream>

#include <string>

#include<fstream>

using namespace std;

int main(int argc, char* argv[])

{

ifstream file ( "D:\\test.csv" ); // declare file stream: http://www.cplusplus.com/reference/iostream/ifstream/

string value;

while ( file.good() )

{

getline ( file, value, ',' ); // read a string until next comma: http://www.cplusplus.com/reference/string/getline/

cout << string( value, 0, value.length() )<<","; // display value removing the first and the last character from it

}

}

读取CSV文件C#

C# 读取CSV文件2009年06月25日 星期四 19:03方法一,纯文本方法,即把该文件当做文本文件读取

int intColCount = 0;

bool blnFlag = true;

DataTable mydt = new DataTable("myTableName");

DataColumn mydc;

DataRow mydr;

string strpath = ""; //cvs文件路径

string strline;

string [] aryline;

System.IO.StreamReader mysr = new System.IO.StreamReader(strpath);

while((strline = mysr.ReadLine()) != null)

{

aryline = strline.Split(new char[]{','});

if (blnFlag)

{

blnFlag = false;

intColCount = aryline.Length;

for (int i = 0; i < aryline.Length; i++)

{

mydc = new DataColumn(aryline[i]);

mydt.Columns.Add(mydc);

}

}

mydr = mydt.NewRow();

for (int i = 0; i < intColCount; i++)

{

mydr[i] = aryline[i];

}

mydt.Rows.Add(mydr);

}

mydt.Rows.RemoveAt(0);

dataGridView1.DataSource = mydt.DefaultView;

dataGridView1.Columns[0].HeaderText = "编号";

方法二、当做一个数据源读取,常用的sql语句都能执行的

using (OleDbConnection conn = new OleDbConnection(@"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=C:\csv\;Extended Properties='Text;'"))

{

DataTable dtTable = new DataTable();

OleDbDataAdapter adapter = new OleDbDataAdapter("SELECT * FROM [Test.csv]", conn);

try

{

adapter.Fill(dtTable);

}

catch (Exception ex)

{

dtTable = new DataTable();

}

this.GridView1.DataSource = dtTable;

this.GridView1.DataBind();

}本回答被网友采纳
相似回答