C++ 如何从文本文件中提取每一行并求平均值?
我有一个问题,我必须阅读文本文件。取每行数字的平均值,然后将这些数字推到一个向量上 70 79 72 78 71 73 68 74 70 78899691949592889592 83819385847978908879 这只是文件的一部分。我不知道该怎么说,我相信这是没有必要的 我已成功打开该文件。我在网上到处都找过如何阅读每一行,并试着平均数字。然而,我总是以失败告终。我是C++初学者,所以我对不太了解很抱歉。p> 如何从文件中提取每一行并求平均值,以便将其推送到向量C++ 如何从文本文件中提取每一行并求平均值?,c++,ifstream,C++,Ifstream,我有一个问题,我必须阅读文本文件。取每行数字的平均值,然后将这些数字推到一个向量上 70 79 72 78 71 73 68 74 70 78899691949592889592 83819385847978908879 这只是文件的一部分。我不知道该怎么说,我相信这是没有必要的 我已成功打开该文件。我在网上到处都找过如何阅读每一行,并试着平均数字。然而,我总是以失败告终。我是C++初学者,所以我对不太了解很抱歉。p> 如何从文件中提取每一行并求平均值,以便将其推送到向量 int main()
int main() {
string inFileName = "lab1.txt";
ifstream inFile;
vector<string> scores;
string myLine2;
openFile(inFile, inFileName);
getAvgofContents(inFile, myLine2);
}
void openFile(ifstream &file, string name){
file.open(name);
while (!file.is_open()) {
cout << "Unable to open default file/file path.\nPlease enter a new file/file path:" << endl;
cin >> name;
file.open(name);
}
cout << "FILE IS OPEN!!!\n";
}
void getAvgofContents(ifstream &file, string line){
while (file){
getline(file, line);
cout << line << endl;
}
}
I am supposed to get results like:
73
81.5
84.1
...
...
Then after averaging each line, push the results to a vector.
这可能有助于:
浮动线{
浮动总数=0;
整数计数=0;
溪流流线;
while1{
int n;
流>>n;
如果!流
打破
总+=n;
计数++;
}
如果计数=0{
//这条线没有号码
返回0;
}
返回总数/计数;
}
float getAvgofContentsifstream&文件,字符串行{
浮动总额;
整数;
当getlinefile{
无法复制您的程序在哪里做了错误的事情/卡住了?是读取文件中的问题,还是查找平均值的问题?@TheZachMan我在查找每行的平均值时遇到了问题。文件读取正确,没有问题。如果我没有说清楚,我很抱歉。谢谢!您在正确的轨道上,但没有getAvgOfLine中没有流的定义。此外,getAvgOfContents中的循环应该是whilegetlinefile,line。@truongminh谢谢你,帮助太多了