how to read in multiple input with loop

Hi all,

Im trying to accomplish reading in a file, perform some calculation and than output the file.

Sample Input file:

Drew Nancy 96 74 77 66 60 55 50 61 79 62
Smith Doug 61 61 54 69 61 78 89 65 61 54
Baker Charlie 93 57 51 61 72 61 57 45 72 78

Sample output file:

Drew Nancy 96 74 77 66 60 55 50 61 79 62 68.00
Smith Doug 61 61 54 69 61 78 89 65 61 54 65.30
Baker Charlie 93 57 51 61 72 61 57 45 72 78 64.70


The last figure on each line is the average of the numbers.

My current method is to

define 12 variables, 2 variable to store the first and last name, the rest of the variables declared as int to store the rest of the values.

I intend to read them line by line...

How can it read the first line, using space as the delimeter and store them in the 12 variables, which i will than calculate the average of only the int and add it to the output (example above) and than continue to the next line.

Or what other method can be used to accomplish this?

Thank all for your help.

Comments

  • To do this in a smooth way, you will want to use arrays. If you don't know how to use them yet, I would suggest looking for information about them. Then the variables would look like this:

    char lastName[20];
    char firstName[20];
    int value[12];

    And the loop (pseudo code):

    [code]
    int i;

    while(we haven't reached end of file)
    {
    read lastName
    read firstName

    for(i=0; i<12; i++)
    {
    value[i] = read a value
    }
    }
    [/code]


    The reading itself is best done with fscanf(). For example, reading a value could be written as:

    fscanf(fp, "%d", &value[i]);

    fscanf() will automatically use whitespaces such as space ' ' or new line '
    ' to separate the integers.
  • i suggest, you use structure of array

    //structure decleration
    struc info
    {
    char lastname[20];
    char firstname[20];
    int grade[10];
    } i;

    void readfile (ifstream & )
    {
    while (not .eof())
    {
    cin >> i.lastname >> i.firstname;
    for (int i = 0; i < 10; i++)
    {
    cin >> i.grade[i];
    }
    }
    }
Sign In or Register to comment.

Howdy, Stranger!

It looks like you're new here. If you want to get involved, click one of these buttons!

Categories