源程序:
#include < iostream >
#include < fstream >
#include < cmath >
#include < vector >
#include < iomanip >
#include < string >
using namespace std;
class Triangle //建立三角形类
{
private:
double sizeA, sizeB, sizeC, area; //三条边、面积
public:
Triangle(double a = 0, double b = 0, double c = 0) //带默认参数的构造函数
{
sizeA = a;
sizeB = b;
sizeC = c;
double p = (sizeA + sizeB + sizeC) *0.5;
area = sqrt(p * (p - sizeA) * (p - sizeB) * (p - sizeC));
}
void set_Tri(double a, double b, double c) //为三条边赋值的函数
{
sizeA = a;
sizeB = b;
sizeC = c;
double p = (sizeA + sizeB + sizeC) *0.5;
area = sqrt(p * (p - sizeA) * (p - sizeB) * (p - sizeC));
}
void set(vector<Triangle> &); //用于输入边长并判断是否合理,最后存入文件
};
//***************************************
//* 成员函数:set
//* 参 数:向量对象的引用
//* 返 回 值:无
//* 功 能:为向量赋值并将向量存入文件
//***************************************
void Triangle::set(vector<Triangle> &v) //向量的类型为Triangle
{
Triangle Tri;
double a, b, c;
while (1)
{
cout << "三角形,边A:";
cin >> a;
if (a == -1)//a的长度输入-1作为结束符
{
ofstream writeFile;
char fileName[20];
cout << "输入要保存到的文件名(加后缀'.txt'):";
cin >> fileName; //输入文件名的时候加入文件名后缀“****.txt”
cout << "保存到文件:" << fileName << endl;
writeFile.open(fileName);
if (writeFile.fail())
{
cout << "没有正确建立文件!" << endl;
return;
}
for (int i = 0; i < v.size(); i++)
{
writeFile << "第" << i + 1 << "个三角形: ";
writeFile << v[i].sizeA << " " << v[i].sizeB << " " << v[i].sizeC << " " << v[i].area << endl;
}
writeFile.close();
cout << "一共写入" << v.size() << "个三角形信息" << endl;
return;
}
cout << "三角形,边B:";
cin >> b;
cout << "三角形,边C:";
cin >> c;
if (a>0 && b>0 && c>0 && ((a + b)>c) && ((a + c)>b) && ((b + c)>a)) //任意两边之和应大于第三边
{
Tri.set_Tri(a, b, c);
v.push_back(Tri);
}
else
cout << "不能组成三角形,重新输入" << endl;
}
}
void main()
{
vector<Triangle> v_tri;
Triangle tri;
tri.set(v_tri);
}
运行结果: