mercredi 4 décembre 2019

C++ double values from CSV file into vector

I have a code that takes a column in the middle of my CSV file and puts all the values in that column into a vector as strings. Is there a way to easily edit this code so the values are changed into doubles before they enter the vector? I keep getting errors with my attempts.

#include<iostream>
#include<fstream>
#include<vector>
#include <sstream>
#include <string>
#include <algorithm>   

std::vector<std::string> readStock(std::string fileName){
   int counter=0;
   std::vector<std::string> temp; //create vector
   std::ifstream f(fileName);
   if(f.is_open()){
     std::string str;
     std::getline(f,str); //skip the first row
     while(std::getline(f,str)){ //read each line
       std::istringstream s(str);  //stringstream to parse csv
       std::string val;  //string to hold value
       for(int i=1;i<12;++i){ //skips until we get to the column that we want
         ++counter;
         std::getline(s,val, ',');

     }
     ++counter;
     std::getline(s,val,',');
     temp.push_back(val);
   }
   f.close();

}

   return temp;
}
int main(){
   std::string ticker;
   std::cin>> ticker;
   ticker +=".csv";
   std::cout<<ticker;
   std::vector<std::string> stock1;
   stock1=readStock(ticker);
   std::cout<<st<<std::endl;
   for(int i=0;i<stock.size();++i){
     std::cout<<stock1[i]<<" ";
   }
   return 0;
}

Aucun commentaire:

Enregistrer un commentaire