尝试将向量写入文件时的Stackdump

时间:2018-04-24 06:19:22

标签: c++ c++11

正确输出但在程序执行时仍然会输出。

  

0 [main]程序12704 cygwin_exception :: open_stackdumpfile:将堆栈跟踪转储到'''program.exe.stackdump

文本文件如下所示

  

U101 77 62 91 95
  U102 73 0 100 62
  U103 0 0 39 55
  U104 84 69 70 100
  U105 93 86 70 0

#include <vector>
#include <fstream>
#include <iostream>
using namespace std;

vector<string> write(vector<string> students, vector<string> student_scores);

vector<string> write(vector<string> students, vector<string> student_scores)
{
    ofstream outfile;
    outfile.open("Data/scores.txt");
    unsigned int count = 0;
    unsigned int exams = student_scores.size() / students.size();
    for (unsigned int i = 0; i <= students.size(); i++) 
    {
        outfile << students[i] << " ";
        outfile.flush();
        for (unsigned int k = 0; k < exams; k++)
        {
            outfile << student_scores[count] << " ";
            count += 1;
            outfile.flush();
        }
        outfile << "\n";

    }
    outfile.close();
    return students;
}

int main()
{
    vector<string> students;
    vector<string> student_scores; 

    students.push_back("U101");
    students.push_back("U102");
    students.push_back("U103");
    students.push_back("U104");
    students.push_back("U105");

    student_scores.push_back("77");
    student_scores.push_back("62");
    student_scores.push_back("91");
    student_scores.push_back("95");

    student_scores.push_back("73"); 
    student_scores.push_back("0");
    student_scores.push_back("100");
    student_scores.push_back("62");

    student_scores.push_back("0");
    student_scores.push_back("0");  
    student_scores.push_back("39");
    student_scores.push_back("55");

    student_scores.push_back("84");
    student_scores.push_back("69");
    student_scores.push_back("70"); 
    student_scores.push_back("100");

    student_scores.push_back("93");
    student_scores.push_back("86");
    student_scores.push_back("70");
    student_scores.push_back("0");  

    write(students, student_scores);
}

1 个答案:

答案 0 :(得分:2)

你绕过一个太多的学生,在这一行:

    for (unsigned int i = 0; i <= students.size(); i++)

您应将其更改为:

    for (unsigned int i = 0; i < students.size(); i++)
    ----------------------------^ removed the equal sign

此外,您不应该使用using namespace std;outfile.close();,因为后者应该依赖RAII