PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Monday, October 31, 2022

[FIXED] How can i read from a file .dat with a lot of lines and gather just few values in arrays until EOF?

 October 31, 2022     arrays, c++, eof     No comments   

Issue

I have to make a program that read from a file .dat that have two columns but i'm interest just to one. Every columun contains a lot of values, stored each ones in line. I want to gather them in groups (arrays) of 120 elements and then calculate the avarage value, proceeding like this until the EOF. Once calculated the avarage i save it in an external file. The code that i wrote is like this:

#include<iostream>
#include<fstream>
#include<string>
#include<sstream>
#include<cmath>

using namespace std;

int i, k=1;
double temp [120];
double tmean, total=0;

int main()
{

ifstream fin ("Data_Acquisition(1).dat");

if (!fin)
{
    cerr << "\nError: the file can't be open.\n" << endl;
    exit(1);
}

string line;

ofstream fout;
fout.open("tmean.dat", ios::out);
fout << "Tmean" << endl;

for(i=0; i<=120; i++)
{
    getline(fin,line);
    istringstream ss(line);    

    double col1;      
    double col2;      

    ss >> col1;  
    ss >> col2;

    temp[i] = col2;
    total += temp[i];
    k++;

}

tmean = total/k;

fout << tmean << endl;

}

My question is: once calculated the avarage of the first group of values, how can i say to the program to continue with others until the file ends?


Solution

You currently have an inner loop...

...
for(i=0; i<=120; i++)
{
    ...
}
tmean = total/k;
fout << tmean << endl;

...just wrap that in an outer for loop...

while (fin >> std::skipws && !fin.eof())
{
    for(i=0; i<=120; i++)
    {
        ...
    }
    tmean = total/k;
    fout << tmean << endl;
}

You might want to fix the bugs too: k starts at 1 and is incremented for each value read, so ends up being 1 more than it should me: start at 0; and Derek's already commented on another issue.



Answered By - Tony Delroy
Answer Checked By - Marilyn (PHPFixing Volunteer)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing