C ++读取数据文件

时间:2019-03-15 23:38:56

标签: c++

我已经成功打开并丢弃了标题。然后,我计算了点1与其他点之间的距离以及最小距离。但是,我不确定如何使代码工作超过4分。我尝试从中提取数据的文本文件如下:

多点坐标(第一行)

x y z(秒)

-0.06325 0.03597 0.042823(第三行)

。 。 。 。 。 。 。 。

续..并且点1具有坐标(-0.06325、0.03597、0.042823)。

另外,我需要告诉您与点1最接近的点以及输出屏幕上点1与最接近点之间的距离,您能帮我吗?谢谢。

#include <iostream>
#include <fstream>
#include <string>
#include <algorithm>
using namespace std;

int main() {

double x1, y1, z1, x2, y2, z2, x3, y3, z3, x4, y4, z4, dist_12, dist_13, 
dist_14, minimum_distance;
ifstream inFile("input-week6-ad-q4-2.txt"); // ifstream function to read the 
file
string line, c; // To read the characters
char ch;


if (inFile.is_open())
{
    getline(inFile, line); // To read the header of the input file then 
discard it
    getline(inFile, line);



    inFile >> x1 >> y1 >> z1;
    inFile >> x2 >> y2 >> z2;
    inFile >> x3 >> y3 >> z3;
    inFile >> x4 >> y4 >> z4;

    int i = 1;
    while (inFile >> xi >> yi >> zi) {

        i++;    
    }
    int number_of_points = i;

    inFile.close();

    }

  else
    cout << "The file could not be opened." << "\n"; // To check for any 
 error

system("pause");
return 0;
 }

1 个答案:

答案 0 :(得分:0)

好问题。如评论中所述,使用ifstream读取长度未知的文件的首选方法是使用类似while (inFile >> xi >> yi >> zi)的文件。

要跟踪最接近的点和距离,请在每次读取后进行检查,并更新最短距离和点索引(如果找到的距离最接近最后一个点)。

由于您已经在使用sqrt(),所以我认为可以使用pow()函数来计算距离公式中的平方。祝您好运,并告诉我这是否有帮助或令人困惑。

#include <iostream>
#include <fstream>
#include <string>
#include <math.h>
#include <vector>

int main()
{
  double xFirst, yFirst, zFirst, xi, yi, zi;
  std::ifstream
      inFile("input-week6-ad-q4-2.txt");
  std::string line; // To read the characters
  double min_distance{UINT_MAX}; // Start with largest distance possible.
  uint closest_point;

  if (inFile.is_open()) {
    // read and discard first 2 lines of file
    getline(inFile, line); getline(inFile, line);

    // Save first point's coordinates
    inFile >> xFirst >> yFirst >> zFirst;
    int i = 1;
    while (inFile >> xi >> yi >> zi) { // safer way to read 3 vars from file
      i++;
      // use the pow(base, power) function for squaring
      double distance = sqrt(pow((xi - xFirst), 2)
                                 + pow((yi - yFirst), 2)
                                 + pow((zi - zFirst), 2));
      if (distance < min_distance) {
        min_distance = distance;
        closest_point = i;
      }
    }
    std::cout << "Read " << i  << " points\n";

    inFile.close();
  }

  std::cout << "The minimum distance is " << min_distance
            << ", which is the distance between point[1] and point["
            << closest_point << "], using 1-based indexing.\n";

  std::cin >> line;
}