ファイル内の整数を不明確にしてベクトルに格納し、最大から最小までソートし、最小のハーモニック平均を求める必要があります最大数。次に、ファイル内の平均値とすべての数値を新しいファイルに出力する必要があります。私は完全に10未満の整数で動作するコードを作成しましたが、文字列としてベクトルに数値を入力し、ファイルの各行を整数として入力するようにコードを書き直す必要がありますが、エラーが発生しています。 "AverageFile"には何も出力されず、ロード後にプログラムがクラッシュします。.txtファイルから数値を取り出してC++のベクトルに入れよう
私のコードの下で、私はこの問題はであると思う:それは "のstd :: bad_allocは何() 'のstd :: bad_alloc' のインスタンスを投げた後に呼び出さTERMINATE" エラーに
を与えますベクトルの入力または出力。
#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'ですか? – Beta
申し訳ありません、 'ofstream'を削除したことを忘れてしまいましたifstream – Uncblueguy