码迷,mamicode.com
首页 > 编程语言 > 详细

C/C++读写csv文件(用getline探测逗号分隔符)

时间:2017-07-28 23:44:20      阅读:906      评论:0      收藏:0      [点我收藏+]

标签:字符   stream   打印   tool   ack   tor   iostream   ret   逗号   

csv文件其实就是文本文件,每行字段用逗号分隔。

 

代码

[cpp] view plain copy
 
 print?
  1. #include <iostream>  
  2. #include <string>  
  3. #include <vector>  
  4. #include <fstream>  
  5. #include <sstream>  
  6.   
  7. using namespace std;  
  8.   
  9.   
  10. int main()  
  11. {  
  12.     // 写文件  
  13.     ofstream outFile;  
  14.     outFile.open("data.csv", ios::out); // 打开模式可省略  
  15.     outFile << "name" << ‘,‘ << "age" << ‘,‘ << "hobby" << endl;  
  16.     outFile << "Mike" << ‘,‘ << 18 << ‘,‘ << "paiting" << endl;  
  17.     outFile << "Tom" << ‘,‘ << 25 << ‘,‘ << "football" << endl;  
  18.     outFile << "Jack" << ‘,‘ << 21 << ‘,‘ << "music" << endl;  
  19.     outFile.close();  
  20.   
  21.     // 读文件  
  22.     ifstream inFile("data.csv", ios::in);  
  23.     string lineStr;  
  24.     vector<vector<string>> strArray;  
  25.     while (getline(inFile, lineStr))  
  26.     {  
  27.         // 打印整行字符串  
  28.         cout << lineStr << endl;  
  29.         // 存成二维表结构  
  30.         stringstream ss(lineStr);  
  31.         string str;  
  32.         vector<string> lineArray;  
  33.         // 按照逗号分隔  
  34.         while (getline(ss, str, ‘,‘))  
  35.             lineArray.push_back(str);  
  36.         strArray.push_back(lineArray);  
  37.     }  
  38.       
  39.     getchar();  
  40.     return 0;  
  41. }  
 

结果

技术分享
 
技术分享
 
http://blog.csdn.net/u012234115/article/details/64465398

C/C++读写csv文件(用getline探测逗号分隔符)

标签:字符   stream   打印   tool   ack   tor   iostream   ret   逗号   

原文地址:http://www.cnblogs.com/findumars/p/7252854.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!