Connecting Tech Pros Worldwide Help | Site Map

trouble with external file usage

Familiar Sight
 
Join Date: Oct 2006
Location: Oklahoma
Posts: 140
#1: Oct 11 '06
I'm having trouble reading the first 2 lines of data in an external file.

I am supposed to use a while loop to read the first 2 lines of an external file that contains several random integers. I think I need 2 loops. I also think it is best not to reinitialize the variables 'sum' and 'num' before the second loop executes.

The overall goal is to read the integers on the 1st 2 lines and compute their sum.

FYI, the data on the 1st 3 lines of the external file is:
21 33 56 725 81
405 628 27
167 254 823 78 63 45

Here's the code I have so far: Please help!!



// read file and compute the average of all integers on the first 2 lines

inFile.open("A: DATFILE1.TXT"); //open DATFILE1.TXT

char inchar = ' '; //assigns inchar to a blank character
sum = num = avg = 0;
count = 1;

inFile>>num;
inFile.get(inchar);
while(inchar !='\n') //this loop is supposed to get the data from the 1st line of data and compute a sum
{
inFile>>num;
count++;
sum = sum + num;
inFile.get(inchar);
}

while(inchar !='\n') //this loop is supposed to get the data from the 2nd line of data and compute the sum
{
inFile>>num;
count++; //NOT GETTING 2nd LINE OF DATA
sum = sum + num;
}

avg = sum/count;

cout<<"The average of the numbers in the 1st 2 lines of data is: "<<avg<<endl<<endl;
outFile<<"The average of the numbers in the 1st 2 lines of data is: "<<avg<<endl<<endl;

inFile.close(); //closes the file for the next calculation
inFile.clear();
Familiar Sight
 
Join Date: Oct 2006
Location: Oklahoma
Posts: 140
#2: Oct 12 '06

re: trouble with external file usage


Nevermind.....Got it.
Reply


Similar C / C++ bytes