0

我有一个内部包含名称和等级的结构,我将使用一个向量来读取文件的内部,直到结构结束。例如:

 struct ReadAll{string name; double numbers;}

 vector <ReadAll>userInfo;

到目前为止,我需要将结果显示在一个文件中,但我需要将它们显示为 ex: student1 89 47 99.. student4 89 78 45.. 但我得到的只是 student4 98 78 45 ... student1 89 47 99.. 我怎样才能以正确的顺序显示它们?

void writeStudents(vector<Student>& students, string outputFileName)    
{//students.push_back(Student());

ofstream outputFile;
outputFile.open(outputFileName.c_str()); 
while(students.size() != 0) 
{

   for (int count = students.size(); count > 0; --count)
   {  
      students.back().average = (students.back().grade1 + 
      students.back().grade2 + students.back().grade3) / 3; 
      outputFile << "size is: "<< students.size() <<endl;
      outputFile << students.back().name <<endl;
      outputFile << students.back().grade1 <<endl;
      outputFile << students.back().grade2 <<endl;
      outputFile << students.back().grade3 <<endl;
      outputFile << "Average: " << students.back().average <<endl;
      students.pop_back();
      //count++;
   }
 }

}

就像现在一样,我只是不知道我必须做什么。

4

2 回答 2

0

通常,C++ 的处理方式要简单得多:

std::ostream& operator<<(std::ostream& outputFile, const student& stud) {
    outputFile << stud.name << '\n';
    outputFile << stud.grade1 << '\n';
    outputFile << stud.grade2 << '\n';
    outputFile << stud.grade3  << '\n';
    outputFile << "Average: " << stud.average <<'\n';
    return outputFile;
}

void writeStudents(vector<Student>& students, const string& outputFileName)    
{    
    std::ofstream outputFile(outputFileName.c_str()); 
    for (int count = 0; count <students.size(); ++count) //why the complexity here?
    {  
        //this line seems like it shouldn't be in a "write" function
        students[i].average = (students[i].grade1 + 
                students[i].grade2 + students[i].grade3) / 3; 
        //This line seems out of place
        outputFile << "size is: "<< students.size() <<'\n'; 
        outputFile << students[i]; 
    }
}

或者,如果您在调用 writeStudents 之前计算了平均值,那么它仍然更简单:

void writeStudents(const vector<Student>& students, const string& outputFileName)    
{    
    //open a file
    std::ofstream outputFile(outputFileName.c_str()); 
    //write number of students 
    outputFile << "size is: "<< students.size() <<'\n'; 
    //copy all of the students to the output file
    std::ostream_iterator<Student> oiter(outputFile)
    std::copy(students.begin(), students.end(), oiter); 
}
于 2013-04-24T16:36:27.257 回答
0

简单的做事方式有什么问题吗?像这样的东西

for (int i = 0; i < students.size(); ++i)
{
    outputFile << students[i].name <<endl;
    outputFile << students[i].grade1 <<endl;
    outputFile << students[i].grade2 <<endl;
    outputFile << students[i].grade3 <<endl;
}

我不明白您为什么要在打印时向后遍历向量并删除项目。这有点奇怪。

于 2013-04-24T16:18:36.443 回答