Hi, I really need help with understanding how to solve an exercise.
Create a new textfile with the name 'studentinfo.txt' and write following and save:

Marie Anderssen
29
Alexander Lind
35
Gholam Payro
32
Zlatan Ibrahimavic
26

Write a program that read the information from 'studentinfo.txt' and calculates the average age.

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

int main()
{
int age;
ifstream read("studentinfo.txt");

if (! read)
   {
         cout<<"File not found!";
         getch();
         return (1);
   }

//Average age calculation supposed to be here I guess...


char vekt[50][30];
   int a, i;
   cout<<"How many new student to you want to add to the list? ";
   cin>>a;
   cin.get();   
   for(i=0; i<a; i++)
   {
      cout<<"Name: ";
      cin.getline(vekt[i],30);
//Need help with adding the age part too..
      
   }
   ofstream outstream("studentinfo.txt", ios::app);
   if(!outstream)
   {
      cout<<"File could not be found!"<<endl;
      return(1);
   }

//calculates new average age..

return 0;
}

Example for how it should look:

Marie Anderssen
29
Alexander Lind
35
Gholam Payro
32
Zlatan Ibrahimavic
26

Average age: 30,5

How many new student to you want to add to the list? 2
Name: Reza Bozorg
Age: 40
Name: Stephanie Meyer
Age: 34

New average age: 32,6666


Would really appreciate it if someone could help me with this one =)

I notice you didn't ask a question. What exactly do you want help with that doesn't correspond to "please give me the solution"?

Edited 5 Years Ago by Narue: n/a

Well I need help understanding how I'm supposed to get the age value from the textfile 'studentinfo.txt' and to calculate the average age.
Also how I'm supposed to add age with the new names in the list..

I need help understanding how I'm supposed to get the age value from the textfile 'studentinfo.txt'

How would you get it from cin? Do the same thing on an ifstream and you're done.

calculate the average age

Do you know how to calculate an average? If not, I'd recommend writing a test program for that sole purpose rather than trying to figure it out within the context of your current more complex program.

Also how I'm supposed to add age with the new names in the list

If you haven't studied structures and classes yet, parallel arrays are a viable option:

string names[N];
int ages[N];

...

for (int i = 0; i < N; i++)
    cout << "Name: '" << names[i] << "' Age: " << ages[i] << '\n';

I'd personally prefer creating a record class that manages the lower level stuff so that your driver can address the tasks rather than piddling details.

I'm sorry but I still don't get it :/ Kind of stressed over this exercise so I'm staring myself blind...

Kind of stressed over this exercise so I'm staring myself blind...

Then walk away. Go do something else, take your mind off the exercise, and come back to it later.

This article has been dead for over six months. Start a new discussion instead.