zoukankan      html  css  js  c++  java
  • C++读取csv表格文件到vector

    这个CSV文件假设知道每行有多少个数,也知道数据的格式,即可使用下面简单的方法实现。

    我们假设每行有4个数据,依次是int,int,float,float

    基本思路是:把每行的数据定为一个类型,放在vector中,方便查找使用。使用FILE读文件,fscanf快速把已知格式的数据读进来。

     1 #include <iostream>
     2 #include <fstream>
     3 #include <vector>
     4 #include <string>
     5 
     6 using namespace std;
     7 
     8 class csvdata{
     9 public:
    10     int id;
    11     int level;
    12     float price;
    13     float cost;
    14 };//行的类定义
    15 
    16 int main()
    17 {
    18     vector<csvdata> incsv;
    19     csvdata intp;
    20     FILE *fp;
    21     fp=fopen("D:\111.csv","r");//你自己的文件路径
    22     while(1){
    23         fscanf(fp,"%d,%d,%f,%f",&intp.id,&intp.level,&intp.price,&intp.cost);
    24         incsv.push_back(intp);
    25         if (feof(fp))break;
    26     }
    27     fclose(fp);
    28     for(int i=0;i<incsv.size();i++)
    29     {
    30         cout<<incsv[i].id<<" "<<incsv[i].level<<" "<<incsv[i].price<<" "<<incsv[i].cost<<endl;
    31         
    32     }//输出显示每行的数据
    33 
    34 
    35 system("pause");
    36 return 0;
    37 }

    如果不知道csv每行的个数和格式类型,也可以统一用string来读取,只是比上面方法稍麻烦。

     1 #include <iostream>
     2 #include <fstream>
     3 #include <sstream>
     4 #include <string>
     5 #include <vector>
     6 
     7 using namespace std;
     8 
     9 string Trim(string& str)
    10 {
    11  str.erase(0,str.find_first_not_of(" 	
    "));
    12 
    13  str.erase(str.find_last_not_of(" 	
    ") + 1);
    14 
    15  return str;
    16 }
    17 
    18 int main()
    19 {
    20  ifstream fin("test.csv");
    21 
    22  string line; 
    23  while (getline(fin, line)) {
    24   //cout << line << endl;
    25 
    26   istringstream sin(line); 
    27   vector<string> fields; 
    28   string field;
    29   while (getline(sin, field, ',')) {
    30    fields.push_back(field); 
    31   }
    32 
    33   string name = Trim(fields[0]); 
    34   string age = Trim(fields[1]); 
    35   string birthday = Trim(fields[2]); 
    36   cout << name << "	" << age << "	" << birthday << endl;
    37  }
    system("pause");
    return 0;
    38 }
  • 相关阅读:
    configure new Linux/Mac
    Python input()和raw_input()的区别
    python json读取txt文本 解析str 出错No JSON object could be decoded
    python TypeError: 'str' object does not support item assignment”
    python中对字典按照value排序
    腾讯实习面试被虐记
    软件里的实践出真知
    c链表实现遇到的错误
    Linux命令(2)
    yum的使用及配置
  • 原文地址:https://www.cnblogs.com/chenzhefan/p/5314516.html
Copyright © 2011-2022 走看看