【发布时间】:2017-04-24 20:03:42
【问题描述】:
我需要在一个文件中取出未知数量的整数并将它们存储到一个向量中,从最大到最小排序并找到最小和最大数字的调和平均值。然后我需要将文件中的平均值和所有数字输出到一个新文件中。我创建了一个代码,该代码非常适合小于十的整数,但它将数字作为字符串输入到向量中,我需要重写代码以将文件的每一行作为整数输入,但出现错误。它不会向“AverageFile”输出任何内容,加载后程序会崩溃。它给出了错误
"在抛出 'std::bad_alloc' 的实例后调用终止 what(): std::bad_alloc"
我的代码如下,我认为问题出在向量的输入或输出上。
#include <iostream>
#include <fstream>
#include <string>
#include<stdlib.h>
#include<vector>
using namespace std;
int main()
{
int line;
vector<int> score;
int i=0;
//double sum=0;
//double avg;
int temp=0;
string x;
cin>>x;
ifstream feederfile(x.c_str());
if(feederfile.is_open())
{
while(feederfile.good())
{
score.push_back(line);
i++;
}
feederfile.close();
}
else cout<<"Unable to open Source file";
//Sorting from greatest to least:
for(int i=0;i<score.size()-1;i++)
{
for(int k=i;k<score.size();k++)
{
if(score[i]<score[k])
{
temp=score[i];
score[i]=score[k];
score[k]=temp;
}
}
}
int a=score[score.size()-1];
int b=score[0];
double abh=2/(1/double (a)+1/double (b));
ofstream myfile ("AverageFile.txt");
if(myfile.is_open())
{
myfile<<"The Harmonic Mean is: "<<abh<<endl;
myfile<<"Sorted Numbers: ";
for(int i=0;i<score.size();i++)
{
if(i<score.size()-1)
{
myfile<<score[i]<<", ";
}
else{myfile<<score[i];}
}
myfile.close();
}
else cout<<"Unable to open Export file";
return 0;
}
【问题讨论】:
-
feederfile应该是ifstream还是ofstream? -
对不起,忘记删除'ofstream'它应该是ifstream