CSV文件C++操作库:MiniCSV

g2b4 6年前

MiniCSV 是一个基于c++文件流的小巧而灵活的 CSV 库。

Writing

We see an example of writing tab-separated values to file usingcsv::ofstreamclass. Tab is a perfect separator to use because it seldom appear in the data. I have once encountered a comma in company name which ruined the CSV processing.

#include "minicsv.h"    struct Product  {      Product() : name(""), qty(0), price(0.0f) {}      Product(std::string name_, int qty_, float price_)           : name(name_), qty(qty_), price(price_) {}      std::string name;      int qty;      float price;  };    int main()  {      csv::ofstream os("products.txt", std::ios_base::out);      os.set_delimiter('\t');      if(os.is_open())      {          Product product("Shampoo", 200, 15.0f);          os << product.name << product.qty << product.price << NEWLINE;          Product product2("Soap", 300, 6.0f);          os << product2.name << product2.qty << product2.price << NEWLINE;      }      os.flush();      return 0;  }

NEWLINEis defined as'\n'. We cannot usestd::endlhere becausecsv::ofstreamis not derived from thestd::ofstream.

Reading

To read back the same file,csv::ifstreamis used andstd::coutis for displaying the read items on the console.

#include "minicsv.h"  #include <iostream>    int main()  {      csv::ifstream is("products.txt", std::ios_base::in);      is.set_delimiter('\t');      if(is.is_open())      {          Product temp;          while(is.read_line())          {              is >> temp.name >> temp.qty >> temp.price;              // display the read items              std::cout << temp.name << "," << temp.qty << "," << temp.price << std::endl;          }      }      return 0;  }


The output in console is as follows.

Shampoo,200,15 Soap,300,6 

项目主页:http://www.open-open.com/lib/view/home/1427182646824