CSV文件C++操作库:MiniCSV

来源:互联网 发布:php 视频直播 开源 编辑:程序博客网 时间:2024/06/07 00:34

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.

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
#include "minicsv.h"
 
structProduct
{
    Product() : name(""), qty(0), price(0.0f) {}
    Product(std::string name_, intqty_, floatprice_)
        : name(name_), qty(qty_), price(price_) {}
    std::string name;
    intqty;
    floatprice;
};
 
intmain()
{
    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();
    return0;
}

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.

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
#include "minicsv.h"
#include <iostream>
 
intmain()
{
    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;
        }
    }
    return0;
}


The output in console is as follows.

Shampoo,200,15 Soap,300,6 

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

0 0
原创粉丝点击