【问题标题】:read csv file in c++ [duplicate]用c ++读取csv文件[重复]
【发布时间】:2017-05-01 04:25:27
【问题描述】:

我有一个 .csv 文件,其中仅包含两列人名和年龄。它看起来像:

Name      Age
Peter     16
George    15.5
Daniel    18.5

我只想在双精度向量中收集人们的年龄。所以我想要类似 vect = {16,15.5,18.5} 的东西。

如果只使用标准库,我怎么能做到这一点?

非常感谢

【问题讨论】:

  • How could I achieve this? 前面应该加上what you have done so far 才能解决问题。
  • 这看起来不像 CSV 文件,而更像是一个固定格式的文件?第一个字段从偏移量 0 开始,第二个字段从偏移量 10 开始?

标签: c++ csv


【解决方案1】:

@BugsFree 感谢您的脚本,但它似乎对我不起作用。

这就是我最终的做法(如果有人感兴趣...)

ifstream infile("myfile.csv");
vector<string> classData;
vector<double> ages;
std::string line;

while (getline(infile, line,'\n'))
{
    classData.push_back(line); //Get each line of the file as a string
}

int s = classData.size();
for (unsigned int i=1; i<s; ++i){
    std::size_t pos = classData[i].find(",");      // position of the end of the name of each one in the respective string
    ages[i-1] = std::stod(classData[i].substr(pos+1,classData[i].size())); // convert string age to a double
}

【讨论】:

  • 您的问题显示,s 的数据。因此,没有人能真正用可行的解决方案来回答。
  • 根据定义,“csv”文件是一个逗号分隔的文件,因此当我处理这样的文件时,这些值显然是用逗号分隔的。我只是举例说明了在 Microsoft Excel 下打开数据时的样子。..
  • 是的,从来没有人对此有过错。同样,您不是以 CSV 格式显示数据,而是以制表符分隔或固定宽度的形式显示数据。如果您对数据的显示和您对 CSV 的一次提及不正确,我们要么需要提出问题以澄清(未回答您澄清的问题),要么猜测您的数据的真实情况。
【解决方案2】:

你可以这样做:

#include <sstream>
#include <string>
#include <fstream>

ifstream infile( "yourfile.csv" ); 
std::vector<double> ages;
while (infile)
{
    std::string line;
    if (!std::getline( infile, line,' ' )) break;
    std::istringstream iss(line);
    string name;
    double age;
    if (!(iss >> name >> age)) { break; }
    ages.push_back(age);
}

【讨论】:

  • 你应该阅读this
猜你喜欢
  • 2016-06-07
  • 2013-04-03
  • 1970-01-01
  • 2016-02-22
  • 2011-06-07
  • 2015-02-07
  • 2018-08-29
  • 2021-07-28
  • 2013-01-21
相关资源
最近更新 更多