首页 > 解决方案 > C++ 将 CSV 文件中的双精度值转换为向量

问题描述

我有一个代码,它在我的 CSV 文件中间取一列,并将该列中的所有值作为字符串放入一个向量中。有没有办法轻松编辑此代码,以便在输入向量之前将值更改为双精度值?我的尝试不断出错。

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

std::vector<double> readStock(std::string fileName){
   int counter=0;
   std::vector<double> 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,',');
     std::size_t hold=0;
     std::stod(val, &hold);
     std::cout<<val<<" ";
     std::cout<<hold<<" ";
   }
   f.close();

}

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

标签: c++c++11

解决方案


将要存储 CSV 数字的向量声明为双精度向量?

std::vector<double> temp;

推荐阅读