- #1
Joon
- 85
- 2
Homework Statement
I have a complete code that calculates distances between point 1(x1,y1,z1) and other points(from 2nd up to more than 100) and the nth point that results in minimum distance and the minimum distance between point 1 and nth point. The code is below.
The code is 100% correct, but it doesn't work when I run on Debugger. I think it is because the code has no access to the actual txt file. How do I pass the filename or the actual file as argv?
Thank you.
Homework Equations
The Attempt at a Solution
C:
#include <iostream>
#include <iomanip>
#include <fstream>
#include <cmath>
#include <limits>
using namespace std;
struct Point3d {
double x, y, z;
};
ostream& operator << (ostream& os, const Point3d& p) {
os << "(" << p.x << ", " << p.y << ", " << p.z << ")";
return os;
}
istream& operator >> (istream& is, Point3d& p) {
is >> p.x >> p.y >> p.z;
return is;
}
double distance(const Point3d &a, const Point3d &b) {
auto squared = pow(a.x - b.x, 2) +
pow(a.y - b.y, 2) +
pow(a.z - b.z, 2);
return sqrt(squared);
}
int main(int argc, char **argv) {
if (argc != 2) {
cerr << "Exactly one argument expected, got " << argc << "\n";
return 1;
}
ifstream inFile(argv[1]);
if (!inFile.is_open()) {
cerr << "error: failed to open '" << argv[1] << "'\n";
return 1;
}
// discard the header line
inFile.ignore(numeric_limits<streamsize>::max(), '\n');
Point3d first_pt;
if (!(inFile >> first_pt)) { // read the first point
cerr << "error: failed read of the first point\n";
return 1;
}
bool other_points = false;
double dist_min = numeric_limits<double>::max();
Point3d closest, current;
while (inFile >> current) { // loop through the other points
other_points = true;
double dist = distance(first_pt, current);
if (dist < dist_min) {
dist_min = dist;
closest = current;
}
}
inFile.close();
if (other_points) {
cout << "closest point to " << first_pt <<
" is " << closest << " [distance: " << dist_min << "]\n";
}
else {
cout << "There was only one point in the file\n";
}
system("pause");
}
Last edited: