external file reads

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • teddarr
    New Member
    • Oct 2006
    • 143

    external file reads

    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("DA TFILE1"); //open DATFILE1.TXT

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

    inFile>>num;
    inFile.get(inch ar);
    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(inch ar);
    }

    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<<en dl;
    outFile<<"The average of the numbers in the 1st 2 lines of data is: "
    <<avg<<endl<<en dl;
    inFile.close(); //closes the file for the next calculation
    inFile.clear();
  • D_C
    Contributor
    • Jun 2006
    • 293

    #2
    You only need one loop.
    Code:
    count = 0;
    while(count < 2)
    {
      inFile>>num;
      inFile.get(inchar);
    
      if(inchar !='\n')
        sum += num;
      else
      {
        count++;
        // is inFile.get(inchar) necessary for '\r' ?
      }
    }

    Comment

    • teddarr
      New Member
      • Oct 2006
      • 143

      #3
      Thanks for the help. I can work with this.

      Comment

      Working...