gpt4 book ai didi

c++ - 从 .txt 文件中获取数字并将它们放入 C++ 中的 vector 中

转载 作者:行者123 更新时间:2023-11-27 22:45:29 25 4
gpt4 key购买 nike

我需要从文件中取出未知数量的整数并将它们存储到一个 vector 中,从大到小排序,然后找到最小和最大数的调和平均值。然后我需要将文件中的平均值和所有数字输出到一个新文件中。我创建了一个代码,该代码非常适用于小于 10 的整数,但它将数字作为字符串输入到 vector 中,我需要重写代码以将文件的每一行作为整数输入,但出现错误。它不会向“AverageFile”输出任何内容,程序会在加载后崩溃。它给出了错误

"terminate called after throwing an instance of 'std::bad_alloc' what(): std::bad_alloc"

我的代码如下,我认为问题出在 vector 的输入或输出上。

#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;
}

最佳答案

您忘记读取文件。在

while(feederfile.good()){
score.push_back(line);
i++;
}

你永远不会从文件中读取,所以你有一个无限循环,因为文件将永远是 good(),最终你会在试图将对象添加到 vector 中时耗尽内存。

使用 feederfile.good() is not what you want to use for your condition .相反,您想使读取操作成为循环条件。所以如果我们这样做,那么我们就有了

while(feederfile >> line){
score.push_back(line);
i++;
}

它将一直读取直到遇到错误或文件结束。

关于c++ - 从 .txt 文件中获取数字并将它们放入 C++ 中的 vector 中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43596788/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com