简体   繁体   中英

How to parse csv file and do arithmetic operations on it using c++?

This is my CSV file and I want to parse this csv data and fetch corresponding columns. Then use fetched columns to carry out some arithmetic operations. This is my code

#include <iostream>
#include <fstream>
#include <sstream>
#include <string>
#include <vector>
//https://ethercalc.org/fo128cmznr

int main()
{
    std::vector <double> vec,vec1;
    std::ifstream theFile("stock.csv");
    std::string symbol,date;
    std::string line;
    double open,high,low,close,adjclose,volume;
    while (getline(theFile, line))
    {
        std::stringstream linestream(line);
        std::getline(linestream, symbol, ',');
        std::getline(linestream, date, ',');
        std::getline(linestream, open, ',');
        std::getline(linestream, high, ',');
        std::getline(linestream, low, ',');
        std::getline(linestream, close, ',');
        std::getline(linestream, adjclose, ',');
        std::getline(linestream, volume, '\n');
        std::cout<<"volume "<<volume<<"\n";
        double sum=(volume+close)/open;
        double rat=(open/high);
        std::cout<<"sum "<<sum<<"\n";
        vec.push_back(sum);
        vec1.push_back(rat);

    }
return 0;
}

Here is the problem; I can parse the data if I converted every variable into a string but then i cant perform arithmetic operations in string form. But if I used other format of variable such as double,float etc then I cant parse the csv file itself. How to solve this problem?

You demonstrated that you know what std::stringstream is, and you know how to use it.

So, take the low , for example. Take this std::string , use it to construct a std::stringstream , then use operator>> to put it into a double , or a float .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM