【问题标题】:Taking numbers from a .txt file and putting them in a vector in c++从 .txt 文件中获取数字并将它们放入 C++ 中的向量中
【发布时间】: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

标签: c++ file vector


【解决方案1】:

您忘记读取文件。在

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

您永远不会从文件中读取,因此您有一个无限循环,因为文件将始终为 good(),最终您在尝试将对象添加到向量中时耗尽内存。

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

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

在遇到错误或文件结尾之前会一直读取。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2015-04-09
    • 2012-11-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-09-28
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多