问题
I have a requirement where i need to search product barcode from a csv file shown below.
Sr. No.,Product Barcode,Product Description,Discount (%),Price Per Unit
1,011001,TOILET PAPER,5,40
2,011002,BATHING SOAP,0,27
3,011003,MOISTURIZER,3,95
4,011004,SHAMPOO,0,115
5,011005,CONDITIONER,5,155
6,011006,TISSUE,10,60
7,011007,HAIR OIL,0,75
8,011008,HAIR GEL,0,96
9,011009,BODY LOTION,7,195
10,011010,FACE WASH,0,85
When the user enters the barcode, it should search the csv file and should pick up the Price per unit as well as discount and generate the bill. This has to be implemented in C++. In the later stage of development I also need to update the csv file content. For instance if it has a column 'Quantity' which shows the stock presence of a particular product, and as that product is sold I need to update the csv field quantity as well.
Please guide me how to search the csv file and pick up the fields. I searched net but could not find satisfactory answer.
I am using Bloodshed Dev C++.
回答1:
I am able to extract the product price for entered barcode and generate the bill, using getline().
Cheers Guys for ur resposes.
回答2:
I would advise using libpcre
You could do something like this --
#include <iostream>
#include <vector>
#include <string>
#include <pcre++.h>
using namespace std;
using namespace pcrepp;
int main(int argc, char **argv) {
string pat = ",";
vector<string> v;
string s;
Pcre p(pat);
int ctr;
while( getline(cin, s) ) {
v = p.split(s);
vector<string>::iterator i;
for(i=v.begin(),ctr=0;i!=v.end();i++,ctr++) {
if(ctr==2) {
cout << *i << endl;
}
}
}
return 0;
}
I agree this might be overkill for extracting the second column or the nth column, but I like this method because pcre gives you a lot of freedom in terms of what text you wish to extract from the CSV file.
来源:https://stackoverflow.com/questions/13756653/handling-csv-files-in-c