Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations strongm on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Reading and processing numbers froma file

Status
Not open for further replies.

Sundevil65

Programmer
Dec 12, 2002
2
US
I'm trying to read a line of numbers from a "file.dat". (i.e., 2 66 78 3 45 23 65). I need to read the value of single digit and count the numbers after it. Of course I'm the fstream ios. Thanks

++++++++++++++++++++++++

#include <iostream.h>
#include <fstream.h>
#include <assert.h>
#include <iomanip.h>


int main ()

{
int reading;

ifstream inStream;
inStream.open(&quot;average.dat&quot;);
assert (inStream.is_open());

while (! inStream.eof()){
inStream >> reading;
int sum = 0;
int i;
int avg = 0;
//int count = 0;
for (int index = 0; index < 5; index++){
sum += reading[0];
//count++;
}
cout << sum << endl;
cout << index << endl;

//avg = sum/index;
//cout << sum << avg << endl;
}
inStream.close();
return 0;
}
 
hi,

I love these types of problems.Its short and easy.Reminds me of the first time Ive programmed. Here you go, hope this helps.

#include<iostream>
#include<fstream>
using namespace std;

void main()
{
ifstream Infile(&quot;dat.txt&quot;);
int Sum=0,Average=0,ReadIn=0,Count=0;

if(!Infile) //Check if file can be opened. cout<<&quot;Cannot open file!&quot;;
Infile>>ReadIn;
while(Infile) // Read file loop
{
Sum = ReadIn + Sum; //Compute Sum.
Infile>>ReadIn;
Count=Count+1;
}
Average = Sum/count; //Compute Average
cout<<&quot;The sum = &quot;<<Sum<<&quot; Average = &quot;<<Average<<endl;
}
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top