There are several problem areas in the code you submitted:
- Hard coded file name. Running your program in a directory that does not have "sample.csv" may cause the
ifstream that you see to crash. - It does not check if
myfile opened successfully. - Loop can access an out-of-range index in
whole_list if "sample.csv" has more rows.
The reorganized code below, although not completely reliable, fixes many of the problems mentioned. That should make you most of the way.
#include <iostream> #include <vector> #include <fstream> #include <sstream> using namespace std; struct Spaxel { int array1; int array2; int red; int blue_o2; int blue_o3; }; ostream& operator << (ostream &os, const Spaxel &rhs) { os << rhs.array1 << ',' << rhs.array2 << ',' << rhs.red << ',' << rhs.blue_o2 << ',' << rhs.blue_o3; return os; } istream& operator >> (istream &is, Spaxel &rhs) { char delim; is >> rhs.array1 >> delim >> rhs.array2 >> delim >> rhs.red >> delim >> rhs.blue_o2 >> delim >> rhs.blue_o3; return is; } int main(int argc, const char *argv[]) { if(argc < 2) { cout << "Usage: " << argv[0] << " filename\n"; return 1; } const char *infilename = argv[argc - 1]; // Reading in the file ifstream myfile(infilename); if(!myfile) { cerr << "Couldn't open file " << infilename; return 1; } vector<Spaxel> whole_list; string line; while( getline(myfile, line) ) { Spaxel data; stringstream linestr (line); linestr >> data; whole_list.push_back(data); cout << data << '\n'; } }
Edit : just to clarify some things from the comment.
As you know, main is the entry point of your program, so no code calls it. Additional optional parameters int argc, const char *argv[] is how parameters and parameters are passed when your program starts with arguments. The first argument to argc indicates how many arguments were passed. The second argv is an array of char * , with each element being an argument passed. The first argument to argv[0] is your program name, and therefore argc always >= 1 .
Suppose you run your sample program from a shell:
./sample sample.csv
then argc and argv will have the following:
argc = 2; argv[0] = "sample" argv[1] = "sample.csv"
So, const char *infilename = argv[argc - 1]; gets the last argument passed, in which the file name should be written.
source share