当前位置:   article > 正文

[C++]c++开源库opencsv用法_open cv c++

open cv c++

跨平台多线程设计!

使用C++分析大数据的时候,数据按CSV格式导出,可以用Excel分析数据。

OpenCSV非常简单易用。

OpenLinyou项目设计跨平台服务器框架,在VS或者XCode上写代码,无需任何改动就可以编译运行在Linux上,甚至是安卓和iOS.

OpenLinyou:https://github.com/openlinyou

跨平台支持

Windows、linux、Mac、iOS、Android等跨平台设计

编译和执行

请安装cmake工具,用cmake可以构建出VS或者XCode工程,就可以在vs或者xcode上编译运行。

源代码:GitHub - openlinyou/opencsv: OpenCSV for C++, Super easy to read and write csv file!

  1. git clone https://github.com/openlinyou/opencsv
  2. cd ./opencsv
  3. mkdir build
  4. cd build
  5. cmake ..
  6. #如果是win32,在该目录出现opencsv.sln,点击它就可以启动vs写代码调试
  7. make
  8. ./test

全部源文件

+ src/opencsv.h

+ src/opencsv.cpp

1.生成csv

  1. #include <assert.h>
  2. #include "opencsv.h"
  3. int main()
  4. {
  5. //make csv
  6. OpenCSV csv = { "ID", "name", "salary" };
  7. csv = { "1", "Jack", "100000" };
  8. csv = { "2", "Tom", "80000" };
  9. csv = { std::to_string(3), "Lucy", "50000" };
  10. std::string buffer1;
  11. csv >> buffer1;
  12. std::string buffer2 = "ID,name,salary\n"
  13. "1,Jack,100000\n"
  14. "2,Tom,80000\n"
  15. "3,Lucy,50000\n";
  16. assert(buffer1 == buffer2);
  17. return 0;
  18. }

2.加载csv

  1. #include <assert.h>
  2. #include "opencsv.h"
  3. int main()
  4. {
  5. std::string buffer2 = "ID,name,salary\n"
  6. "1,Jack,100000\n"
  7. "2,Tom,80000\n"
  8. "3,Lucy,50000\n";
  9. OpenCSV csv;
  10. csv << buffer2;
  11. std::string buffer1 = "ID,name,salary\n";
  12. for (size_t i = 1; i < csv.size(); ++i)
  13. {
  14. auto& line = csv[i];
  15. buffer1.append(line["ID"] + "," + line["name"] + "," + line["salary"] + "\n");
  16. }
  17. assert(buffer1 == buffer2);
  18. return 0;
  19. }

3.生成和加载csv文件

  1. #include <assert.h>
  2. #include "opencsv.h"
  3. int main()
  4. {
  5. std::string buffer1;
  6. std::string buffer2;
  7. buffer2 = "ID,name,salary\n"
  8. "1,Jack,100000\n"
  9. "2,Tom,80000\n"
  10. "3,Lucy,50000\n";
  11. std::string filePath = "./test.csv";
  12. //make csv file
  13. {
  14. OpenCSV csv;
  15. csv << buffer2;
  16. assert(csv[0][0] == "ID");
  17. assert(csv[0][2] == "salary");
  18. csv[1]["salary"] = std::to_string(10000);
  19. csv[2]["salary"] = "8000";
  20. csv[3]["salary"] = "5000";
  21. csv >> filePath;
  22. }
  23. buffer2 = "ID,name,salary\n"
  24. "1,Jack,10000\n"
  25. "2,Tom,8000\n"
  26. "3,Lucy,5000\n";
  27. //read csv file
  28. {
  29. OpenCSV csv;
  30. csv << filePath;
  31. buffer1.clear();
  32. csv >> buffer1;
  33. }
  34. assert(buffer1 == buffer2);
  35. return 0;
  36. }
声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/你好赵伟/article/detail/959235
推荐阅读
相关标签
  

闽ICP备14008679号