Storing the data in 18 independent variables is awkward. The naming of your variables suggests that each group of six double
s represents an object, which I've called a Sexdoublet
.
Throwing all the code into main()
is poor practice; there should be a function to do the importing. It should accept an istream
parameter and return a vector
of Sexdoublet
s.
I don't know what you were hoping to accomplish with if (!ifs) ifs >> trash;
— if the ifstream
is bad then you shouldn't try reading from it.
Hard-coding the filename is probably a bad idea. I've used the convention of reading from either a file that is specified on the command line, or from standard input otherwise.
#include <fstream>
#include <iostream>
#include <string.h>
#include <vector>
/* A struct of six doubles */
struct Sexdoublet {
double x, y, d, m, c, t;
friend std::istream &operator>>(std::istream &in, Sexdoublet &r) {
return in >> r.x >> r.y >> r.d >> r.m >> r.c >> r.t;
}
friend std::ostream &operator<<(std::ostream &out, const Sexdoublet &r) {
return out << "[ x = " << r.x
<< ", y = " << r.y
<< ", d = " << r.d
<< ", m = " << r.m
<< ", c = " << r.c
<< ", t = " << r.t << " ]";
}
};
std::vector<Sexdoublet> import(std::istream &in) {
std::vector<Sexdoublet> data;
Sexdoublet s;
while (in >> s) {
data.push_back(s);
}
return data;
}
int main(int argc, char *argv[]) {
// If the first command-line argument is not "-", treat it as the filename
// from which to read the input. Otherwise, read from STDIN.
const char *filename = (argc >= 2 && 0 != strcmp("-", argv[1])) ?
argv[1] : NULL;
std::ifstream f;
std::istream &in = filename ? (f.open(filename), f) : std::cin;
if (!f) {
std::cerr << "Error opening " << filename << ": "
<< strerror(errno) << std::endl;
return 1;
}
std::vector<Sexdoublet> data = import(in);
std::for_each(data.begin(), data.end(), [](const Sexdoublet &s) {
std::cout << s << std::endl;
});
return 0;
}