By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
432,650 Members | 1,823 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 432,650 IT Pros & Developers. It's quick & easy.

external file reads

100+
P: 143
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.

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("DATFILE1"); //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();
Oct 10 '06 #1
Share this Question
Share on Google+
2 Replies


100+
P: 293
D_C
You only need one loop.
Expand|Select|Wrap|Line Numbers
  1. count = 0;
  2. while(count < 2)
  3. {
  4.   inFile>>num;
  5.   inFile.get(inchar);
  6.  
  7.   if(inchar !='\n')
  8.     sum += num;
  9.   else
  10.   {
  11.     count++;
  12.     // is inFile.get(inchar) necessary for '\r' ?
  13.   }
  14. }
Oct 11 '06 #2

100+
P: 143
Thanks for the help. I can work with this.
Oct 12 '06 #3

Post your reply

Sign in to post your reply or Sign up for a free account.