zoukankan      html  css  js  c++  java
  • 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
  • 相关阅读:
    utf8.php
    common.php
    ubuntu 12.04 下 Vim 插件 YouCompleteMe 的安装
    Linux 获取文件夹下的所有文件
    poj 1659 Frogs' Neighborhood Havel-Hakimi定理 可简单图定理
    Huffman Coding 哈夫曼编码
    hdu 4778 Gems Fight! 博弈+状态dp+搜索
    print neatly 整齐打印 算法导论
    poj 2533 Longest Ordered Subsequence 最长递增子序列
    poj 3783 Balls 动态规划 100层楼投鸡蛋问题
  • 原文地址:https://www.cnblogs.com/findumars/p/7252854.html
Copyright © 2011-2022 走看看