CSV文件C++操作庫:MiniCSV
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
本文由用戶 g2b4 自行上傳分享,僅供網友學習交流。所有權歸原作者,若您的權利被侵害,請聯系管理員。
轉載本站原創文章,請注明出處,并保留原始鏈接、圖片水印。
本站是一個以用戶分享為主的開源技術平臺,歡迎各類分享!