C++简单的文件读写操作 -----(笔记)
#include<iostream>
#include<fstream>
#include<string>
#include<vector>
#include<cmath>
#include<climits>
#include <iomanip>
using namespace std;
class Point{
private:
char name;
double x;
double y;
public:
Point(char t_name,double t_x,double t_y)
:name(t_name),y(t_y),x(t_x){}
char getName(){
return name;
}
double getX(){
return x;
}
double getY(){
return y;
}
};
int main(){
ifstream infile;
infile.open("point.txt");
double cmin = INT_MAX;
vector<Point> vector;
while(!infile.eof()){
char name;
double x;
double y;
//文件内每行格式为 A 1.5 2.5
infile >> name >> x >> y;
Point p(name,x,y);
vector.push_back(p);
}
infile.close();
ofstream outfile;
outfile.open("out.txt");
for(int i=0;i<vector.size();i++){
for(int j=i+1;j<vector.size();j++){
if(outfile.is_open()){
double width = sqrt(pow(vector[i].getX()-vector[j].getX(),2)+pow(vector[i].getY()-vector[j].getY(),2));
cmin = min(cmin,width);
outfile << vector[i].getName() << "->" << vector[j].getName() << ": " << width << "\n";
}
}
}
outfile << "最短距离为:" << cmin << "\n";
outfile.close();
}
测试样例 point.txt
A 2.4 3.5
B 5.4 1.6
C 5.7 8.3
D 6.3 5.2
输出文件 out.txt
A->B: 3.55106
A->C: 5.82495
A->D: 4.25441
B->C: 6.70671
B->D: 3.7108
C->D: 3.15753
最短距离为:3.15753