首页 > 解决方案 > 从 CSV 文件中读取数据并尝试将数据加载到由结构组成的向量中?

问题描述

我有一个名为“Sample.csv”的 .csv 文件,看起来像这样

0 60
1 61
2 62
3 63

我正在尝试将第一列读取为小时(int),将第二列读取为温度(double)。我将小时数和温度设置为一个名为“Reading”的结构,并有一个由这些读数组成的向量,称为“temps”。当我运行我的程序时,它不返回任何内容,并且 temps 的大小为 0。

我知道正在读取 csv 文件,因为我的错误消息没有弹出并且在玩弄它时我让它返回“0 ,0”一次。

struct Reading {
    int hour;
    double temperature;
};

vector<Reading> temps;
int main() {
    int hour;
    double temperature;
    ifstream ist("Sample.csv");
    if (!ist) {
        cerr << "Unable to open file data file";
        exit(1);   // call system to stop
    }
    while (ist >> hour >> temperature) {
        if(hour < 0 || 23 < hour) error("hour out of range");
        temps.push_back(Reading{hour,temperature});
    }
    for (int i=0;i<temps.size();++i){
        cout<<temps[i].hour<<", "<<temps[i].temperature<<endl;
    }
    cout<<temps.size();
    ist.close();
}

我期待:

0, 60
1, 61
2, 62
3, 63 
4

我的实际输出是:

0

标签: c++csv

解决方案


通过更正几个括号的位置,代码会产生预期的结果:

#include <iostream>
#include <fstream>
#include <sstream>
#include <cerrno>
#include <vector>

using namespace std;

struct Reading {
    int hour;
    double temperature;
};

vector<Reading> temps;

int main()
{
  int hour;
  double temperature;
  ifstream ist("Sample.csv");
  if (!ist) {
    cerr << "Unable to open file data file";
    exit(1);   // call system to stop
  }
  while (ist >> hour >> temperature) {
    if (hour < 0 || 23 < hour) {
      std::cout << "error: hour out of range";
    } else {
      temps.push_back(Reading{hour, temperature});
    }
  }
  for (int i = 0; i < temps.size(); ++i) {
    cout << temps[i].hour << ", " << temps[i].temperature << endl;
  }
  cout << temps.size();
  ist.close();
}

输出

0, 60
1, 61
2, 62
3, 63
4
Process finished with exit code 0

推荐阅读