C/C++讀寫csv文件(用getline探測逗號分隔符)


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


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM