如何从文本文件中获取每一行并平均它们?

Posted

技术标签:

【中文标题】如何从文本文件中获取每一行并平均它们?【英文标题】:How do I take each line from a text file and average them? 【发布时间】:2019-01-17 03:32:36 【问题描述】:

我有一个问题,我必须读取文本文件。取每一行数字,平均数字,然后将这些数字推入一个向量。

70 79 72 78 71 73 68 74 75 70

78 89 96 91 94 95 92 88 95 92

83 81 93 85 84 79 78 90 88 79

这只是部分文件。不知道怎么放,肯定没必要。

我已成功打开文件。我在网上到处查看如何阅读每一行并尝试平均数字。然而,我总是以失败告终。我是 C++ 的初学者,所以很抱歉我知道的不多。

如何从文件中取出每一行并对它们进行平均以便将其推送到向量?

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.

【问题讨论】:

Read file line by line using ifstream in C++的可能重复 您的程序在哪里做错事/卡住了?问题是在文件中读取还是找到平均值? @TheZachMan 我在查找每行的平均值时遇到问题。该文件正确读取,没有问题。如果我没有说清楚,我很抱歉。谢谢! 【参考方案1】:

这可能会有所帮助:

float getAvgOfLine(string line) 
  float total = 0;
  int count = 0;
  stringstream stream(line);
  while(1) 
   int n;
   stream >> n;
   if(!stream)
      break;
   total += n;
   count++;
  
  if (count == 0) 
     // the line has no number
     return 0;
  
  return total/count;


float getAvgofContents(ifstream &file, string line)
    float total;
    int number;
    while (getline(file, line))
        cout << getAvgOfLine(line)<< endl;
    

参考:Convert String containing several numbers into integers

【讨论】:

你在正确的轨道上,但在getAvgOfLine 中没有stream 的定义。另外,getAvgOfContents 中的循环应该是while(getline(file, line)) @truongminh 谢谢你,大量的帮助

以上是关于如何从文本文件中获取每一行并平均它们?的主要内容,如果未能解决你的问题,请参考以下文章

从 RichTextBox 中的每一行获取文本?

从包含 url 的文本文件中获取 url 的文件大小

为啥当我将文本从浏览器复制并粘贴到文件时,Vim 会再次缩进每一行?

输出是一个文本文件,每一行第一个数字式行标,第二个数字是输入文件中每一行除行标外数字的平均值

在java中如何修改文本文件中的某一行的某些数据??

如何在文件处理中从文本文件中找到每一行的最小值和最大值?