C++ 读取CSV文件并尝试将数据加载到由结构组成的向量中?

C++ 读取CSV文件并尝试将数据加载到由结构组成的向量中?,c++,csv,C++,Csv,我有一个名为“Sample.csv”的.csv文件,看起来像这样 0 60 1 61 2 62 3 63 我试图把第一列读作小时(int),第二列读作温度(double)。 我把时间和温度设置成一个叫做“读数”的结构,还有一个由这些读数组成的向量叫做“温度”。 当我运行我的程序时,它不会返回任何内容,temp的大小为0 我知道csv文件正在被读取,因为我的错误消息没有弹出,在玩它时,我让它返回“0,0”一次 我的实际产出是: 0 通过更正两个括号的位置,代码将生成预期结果: #include

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

0 60
1 61
2 62
3 63
我试图把第一列读作小时(int),第二列读作温度(double)。 我把时间和温度设置成一个叫做“读数”的结构,还有一个由这些读数组成的向量叫做“温度”。 当我运行我的程序时,它不会返回任何内容,temp的大小为0

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

我的实际产出是:

0

通过更正两个括号的位置,代码将生成预期结果:

#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();
}

请发布可编译代码。我最好的猜测是问题在于测试文件的编码。确保它是ascii。
通过纠正几个括号的位置
我只看到
else{}
部分是正确的,但在这个测试用例中它不应该真的有任何区别(因为所有的小时都是有效的)。我错过了什么吗?我仍然只收到0。我将再次检查文件是否已正确读取和打开。这是目前我唯一能想到的。我明天再打给你。感谢您的评论!
0
#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