我正在研究这个项目,我无法弄清楚如何将所有信息输出到文本文件中,它似乎只输出输入的最后一点信息。在平均输出之前输入新标题之前,我只能设法让它将平均值放在文本文件中。请帮帮我!
#include <iostream>
#include <fstream>
#include <vector>
#include <string>
using namespace std;
class FamilyMember
{
private:
int age;
string name;
public:
FamilyMember();
~FamilyMember(){}
void setName(string memberName)
{name = memberName;}
void setAge(int memberName)
{age = memberName;}
int getAge()
{return age;}
string getName()
{return name;}
void printFamilyMemberInfo();
};
FamilyMember::FamilyMember()
{
age = 0;
}
void FamilyMember::printFamilyMemberInfo()
{
ofstream dataFile;
dataFile.open("myFamily.txt", ios::out);
dataFile << name << endl;
dataFile << age << endl;
}
int main()
{
vector<FamilyMember> list;
string Name;
int Age, x, n;
fstream dataFile;
FamilyMember *c;
cout << "Input number of family members";
cin >> x;
for(n = 0; n < x; n++)
{
cout << "Enter name:";
cout << endl;
cin >> Name;
cout << "Enter age:";
cout << endl;
cin >> Age;
c = new FamilyMember;
c->setName(Name);
c->setAge(Age);
list.push_back(*c);
}
vector<FamilyMember>::iterator v;
for(v = list.begin(); v != list.end(); ++v){
v->printFamilyMemberInfo();
}
double a, b;
for(n = 0; n < x; n++)
{
a += list.at(n).getAge();
}
b = a / x;
std::ofstream datafile("myFamily.text", std::ios_base::out | std::ios_base::app);
dataFile << "Average age is: " << b << endl;
return 0;
}
答案 0 :(得分:0)
尝试在追加模式下打开流而不是ios::out
void FamilyMember::printFamilyMemberInfo()
{
ofstream dataFile;
dataFile.open("myFamily.txt", ios::app); // OPEN IN APPEND MODE
dataFile << name << endl;
dataFile << age << endl;
}