简体   繁体   中英

Reading from a CSV file and trying to load the Data into a Vector composed of Structs?

I have a .csv file named "Sample.csv" that looks like this

0 60
1 61
2 62
3 63

I'm trying to read the first column as hours (int) and the second column as the temperature (double). I have the hours and temperature set up as a struct called "Reading" and have a vector made up of these readings called "temps". When I run my program, it doesn't return anything and the size of temps is 0.

I know that the csv file is being read because my error message doesn't pop up and in playing around with it I got it to return "0 ,0" once.

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

I was expecting:

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

My actual output was:

0

By correcting the positioning of a couple of your parenthesis, the code produces your expected result:

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

Output

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM