2d array

I have a student's grades data which is a text file that contains 10 records, each containing 6 columns.

I need to wrie a program to read the content line by line from the text file into a 2d array.

How to ask a person which student he/she want to see the record then print the records only what the person is looking for?

How to read from text file and store records into 2d array in c++?

How to calculate and print the grade average and mid term grade for each student?

How to calculate and print the average grade of all students for each grade and exam?

How to sort and print the ids and grades in order by ascending id number?

How to sort and print the ids and grades in order of descending grades?

How to chang the grade for a student?

AFabriziAsked:
Who is Participating?
 
smpoojaryConnect With a Mentor Commented:
I have written some part of your code. It is working fine. Otherthings (other part) you have to do with yourself. Any doubt you can ask us.

student.h
--------------
#ifndef __STUDENT_H
#define __STUDENT_H

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

const unsigned int SUCCESS            =0;
const unsigned int ERROR_UNOPEN      =1;

class StdDBase
{
      fstream fptrData;

      int i, j, SelRollNo, lab1, lab2, lab3, lab4;
      int option;
      float midtermgrade;
      float nTotalRec, NewGrade, nTotalNo;

      struct student
      {
            long uRollNo;
            float fLab1;
            float fLab2;
            float fLab3;
            float fLab4;
            float fExamGrade;
            float fMidtermGrade;
            float fAvgGrade;
      } stdRec;


public:
      StdDBase();
      //Create the student database (file with records)
      bool CreateDatabase(); //Return false if unable to create student database

      //How to read from text file and store records into 2d array in c++?
      void ReadStdDatabase();

      //How to calculate and print the grade average and mid term grade for each student?
      void CalGradeAvg(); //Update all records in database(file) also

      //How to calculate and print the average grade of all students for each grade and exam?
      void CalGradeAvgAllStd(); //Update all records in database also

      //How to ask a person which student he/she want to see the record then print the records only what the person is looking for?
      bool GetStdRecord(); //return false if record is not exists

      //How to sort and print the ids and grades in order by ascending id number?
      void SortToAscStdDBase();

      //How to sort and print the ids and grades in order of descending grades?
      void SortToDescStdBase();

      //How to chang the grade for a student?
      bool ChangeGrade();      //Return false if record is not exists
                        //Update modified student record in database
      void DisplayDabase();
      ~StdDBase();
};

#endif

student.cpp
--------------
#include "student.h"

StdDBase::StdDBase()
{

      fptrData.open("stdDBase.txt",ios::in | ios::out | ios::binary);
}

bool StdDBase::CreateDatabase()
{
      int nTotal;
      if(!fptrData.is_open())
      {
            //cout << endl << "Unable to open input file stdDBase.txt" << endl;
            return ERROR_UNOPEN;
      }

      cout << "How many records you want to add : ";
      cin >> nTotal;

      fptrData.seekp(0,ios::beg);
      for(int i=0; i<nTotal; ++i)
      {
            cout << "Enter RollNo : ";
            cin >> stdRec.uRollNo;
            cout << "Enter Lab1 marks : ";
            cin >> stdRec.fLab1;
            cout << "Enter Lab2 marks : ";
            cin >> stdRec.fLab2;
            cout << "Enter Lab3 marks : ";
            cin >> stdRec.fLab3;
            cout << "Enter Lab4 marks : ";
            cin >> stdRec.fLab4;
            cout << "Enter Exam Grade : ";         //Better to Calculate ExamGrade
            cin >> stdRec.fExamGrade;
            stdRec.fMidtermGrade = 0.0;
            stdRec.fAvgGrade = 0.0;
            fptrData.write((const char *)&stdRec,sizeof(stdRec));
      }


      return SUCCESS;
}
void StdDBase::DisplayDabase()
{
      fptrData.clear();
      fptrData.seekg(0,ios::beg);
      cout << "Roll No\tLab1\tLab2\tLab3\tLab4\tExam Grade\tMidterm Grade\tAvg. Grade" << endl;
      while(!fptrData.eof())
      {
            memset(&stdRec,0,sizeof(stdRec));
            fptrData.read((char *)&stdRec,sizeof(stdRec));
            if(fptrData.gcount() == 0)
                  break;
            cout << stdRec.uRollNo << '\t' << stdRec.fLab1 << '\t' << stdRec.fLab2 << '\t'
                  << stdRec.fLab3 << '\t' << stdRec.fLab4 << '\t' << stdRec.fExamGrade << '\t'
                  << stdRec.fMidtermGrade << '\t' << stdRec.fAvgGrade << endl;
      }
}
StdDBase::~StdDBase()
{
      fptrData.close();
}
void StdDBase::CalGradeAvg()
{
      fptrData.clear();
      fptrData.seekg(0,ios::beg);
      int i=0;

      while(!fptrData.eof())
      {
            memset(&stdRec,0,sizeof(stdRec));
            fptrData.read((char *)&stdRec,sizeof(stdRec));
            if(fptrData.gcount() == 0)
                  break;

        stdRec.fAvgGrade = ((.05 * stdRec.fLab1) +
        (.1 * stdRec.fLab2) + (.1 * stdRec.fLab3) +
        (.25 * stdRec.fLab4))/4;
       
        stdRec.fMidtermGrade = stdRec.fAvgGrade + stdRec.fExamGrade;

            fptrData.seekp(i*sizeof(stdRec),ios::beg);

            fptrData.write((const char*)&stdRec,sizeof(stdRec));
            fptrData.flush();

            ++i;
      }
}
void StdDBase::CalGradeAvgAllStd()
{

}
bool StdDBase::GetStdRecord()
{

      return SUCCESS;
}
void StdDBase::ReadStdDatabase()
{

}

void StdDBase::SortToAscStdDBase()
{

}
void StdDBase::SortToDescStdBase()
{

}
bool StdDBase::ChangeGrade()
{

      return SUCCESS;
}                  

int main()
{

      int nCh;
      StdDBase stdObj;

      do
      {
            cout << "1->Create Student Database" << endl;
            cout << "2->Calculate Grade Average and Midterm Grade " << endl;
            cout << "3->Calculate Average Grade of all students " << endl;
            cout << "4->Select Record to read " << endl;
            cout << "5->Sort Records in Ascending order " << endl;
            cout << "6->Sort Records in Descending order " << endl;
            cout << "7->Change Grade of a student " << endl;
            cout << "8->Display Database " << endl;
            cout << "Choose : ";
            cin >> nCh;
            switch(nCh)
            {
            case 1:
                  if(stdObj.CreateDatabase()!=SUCCESS)
                  {
                        cout << endl << "Unable to open data base " << endl;
                        return ERROR_UNOPEN;
                  }

                  break;
            case 2:
                  stdObj.CalGradeAvg();
                  break;
            case 3:
                  break;
            case 4:
                  break;
            case 5:
                  break;
            case 6:
                  break;
            case 7:
                  break;
            case 8:
                  stdObj.DisplayDabase();
                  break;
            }
      }while(nCh <= 8);
                  
      return 0;
}


-Mahesh
0
 
r-kCommented:
Is this homework?
0
 
smpoojaryCommented:
>>How to ask a person which student he/she want to see the record then print the records only what the person is looking for?

    Based on student Roll No (Enrolment No or Registration No) you can get the record from the file and display the record contents of that person. If your file contents are in unformatted structure then you can use seekg() or seekp() Otherwise read the file from beginning (sequentially to end) of the file and check record Roll No and display the contents.

      struct student
                {
            using long RollNo;
            char Name[30];
            float Exam1;
            float Exam2;
            float Exam3;
            float AvgGrade;
            //.......other fields.......
               }stdRec;

      cout << "Enter Roll No of the student to check his Average Grade : ";
      cin >> SelRollNo;
               ifstream in("std.dat",ios::in|ios::binary);
               if(!in)
               {
                    cout << "Cannot open input file.\n";
                    return 1;
                }
      cout << "Roll No.\tName\tExam1\tExam2\tExam3\tAverage Grade\t..............\n";
      in.seekg(0,ios::beg);    //No need
      while(!in.eof())
      {
            in.read((char *)&stdRec,sizeof(stdRec));
            if(in.gcount() == 0) break;
            if(stdRec.RollNo == SelRollNo)
            {
                  cout << stdRec.RollNo << "\t" << stdRec.Name << "\t" << stdRec.Exam1 << "\t <<
                        stdRec.Exam2 << "\t" << stdRec.Exam3 << "\t" << stdRec.AvgGrade << endl;
                  break;
            }
      }
      
>>How to read from text file and store records into 2d array in c++?

    No need 2d Array. 1-d Array of 1000 student records is sufficient.

      struct student aStdRec[1000];
      in.seekg(0,ios::beg);
      int i=0;
      while(!in.eof())
      {
            in.read((char *)&aStdRec[i],sizeof(struct student));

            if(in.gcount() == 0) break;
            ++i;
      }
      nTotalRec = i;

>>How to calculate and print the grade average and mid term grade for each student?

      int i=0;
      while(i<=nTotalRec)
      {
            aStdRec[i].AvgGrade = (aStdRec[i].Exam1 + aStdRec[i].Exam2 + aStdRec[i].Exam3)/3;//Some other formula
            cout << aStdRec[i].RollNo << "\t" << aStdRec[i].Name << "\t" << aStdRec[i].AvgGrade << endl;
            ++i;
      }

>>How to calculate and print the average grade of all students for each grade and exam?
      AvgAllGrade1=0;
      AvgAllGrade2=0;
      AvgAllGrade3=0;
      while(i<=nTotalRec)
      {
            AvgAllGrade1 += aStdRec[i].Exam1;
            AvgAllGrade2 += aStdRec[i].Exam2;
            AvgAllGrade3 += aStdRec[i].Exam3;
            ++i;
      }

      AvgAllGrade1 /= (nTotalRec+1);
      AvgAllGrade2 /= (nTotalRec+1);
      AvgAllGrade3 /= (nTtoalRec+1);

>>How to sort and print the ids and grades in order by ascending id number?
//Consider id as RollNo
//Sor in Ascending order
      struct student temp;
      for(i=0;i<nTotalNo;++i)
            for(j=i+1;j<=nTotalNo;++j)
      {
                  if(aStdRec[i].RollNo > aStdRec[j].RollNo)
                  {
                        temp = aStdRec[i];   //Better to use 'operator =' overloading
                        aStdRec[i] = aStdRec[j];
                        aStdRec[j] = temp;
                  }
      }
//Print the result
      int i=0;
      while(i<=nTotalRec)
      {
            cout << aStdRec[i].RollNo << "\t" << aStdRec[i].Name << "\t" << aStdRec[i].AvgGrade << endl;
            ++i;
      }

>>How to sort and print the ids and grades in order of descending grades?
In above code only change
      if(aStdRec[i].RollNo > aStdRec[j].RollNo)
to
      if(aStdRec[i].RollNo < aStdRec[j].RollNo)

>>How to chang the grade for a student?
                cout << "Which student grade you want to change : ";
      cin >> SelRollNo;
      cout << "Enter his grade : ";
      cin >> NewGrade;
      int i=0;
      while(i<=nTotalRec)
      {
            if(aStdRec[i].RollNo == SellRollNo)
                  aStdRec[i].AvgGrade = NewGrade;
            ++i;
      }
0
Cloud Class® Course: Amazon Web Services - Basic

Are you thinking about creating an Amazon Web Services account for your business? Not sure where to start? In this course you’ll get an overview of the history of AWS and take a tour of their user interface.

 
r-kCommented:
smpoojary:

we should avoid doing homework for students, esp. when they have no effort at all on their own.
0
 
smpoojaryCommented:
Sorry. I didn't think about this.
-Mahesh
0
 
AFabriziAuthor Commented:
No this is not homework, this is practice before the test
0
 
smpoojaryCommented:
Good
0
 
AFabriziAuthor Commented:
This program is not working.

I need this to be work or otherwise I will not be ready for test.

Please make this works.

#include <iostream.h>
#include <conio.h>
#include <iomanip.h>
#include <fstream.h>
#include <stdlib.h>

int main()
{
    char file1[21];
    int i, j, SelRollNo, lab1, lab2, lab3, lab4;
    int option;
    float midtermgrade;
    float nTotalRec, NewGrade, nTotalNo;
   
    struct student
    {
           long RollNo;
           float lab1;
           float lab2;
           float lab3;
           float lab4;
           float examgrade;
           float AvgGrade;
    } stdRec;
   
    ifstream input;
   
    ofstream output("a:lab8-output.txt");
   
    cout << "Please enter the name of the file you wish to open: ";
    cin >> file1;
   
    input.open(file1);
   
    if(input.fail()) exit(1);

cout << "Enter Roll No of the student to check his/her Grades: ";
cin >> SelRollNo;

cout << "Student ID# " << "lab1 " << "lab2 " << "lab3 " << "lab4 " << "Exam " << "Lab Average" << endl;
cout << "-------------- " << "----- " << "----- " << "----- " << "---- " << "------ " << "---------------" << endl;

do
{
   
cout << "\nWelcome to the Mid-term grading program" << endl;
cout << "1 - Print out the inputted grade and id information" << endl;
cout << "2 - Calculate and print the lab grade average and mid term grade for "
<< "each student" << endl;
cout << "3 - Calculate and print the average grade of all students for each "
<< "lab and the exam" << endl;
cout << "4 - Sort and print the ids and grades in order by ascending id number"
<< endl;
cout << "5 - Sort and print the ids and grades in the order of descending grades"
<< endl;
cout << "6 - Change the grade for a student" << endl;
cout << "7 - End Program" << endl;

cout << "Enter Option: ";
cin >> option;
cout << endl;

if(option == 1)
{    
    i = 0;
    while(!input.eof())
    {
        input.read((char*)&stdRec,sizeof(stdRec));
       
        if(input.gcount() == 0) break;
       
        if(stdRec.RollNo == SelRollNo)
        {
            cout << stdRec.RollNo << "\t" << stdRec.lab1 << "\t"
            << stdRec.lab2 << "\t" << stdRec.lab3 << "\t"
            << stdRec.lab4 << "\t" << stdRec.examgrade << "\t"
            << stdRec.AvgGrade << endl;
            break;
        }
    }
   
struct student aStdRec[10];
input.seekg(0,ios::beg);

i = 0;
while(!input.eof())
{
    input.read((char*)&aStdRec[i],sizeof(struct student));
   
    if(input.gcount() == 0) break;
    i++;
}
nTotalRec = i;
}// end option 1    

if(option == 2)
{
    i = 0;
    while(i <= nTotalRec)
    {
            aStdRec[i].AvgGrade = ((.05 * aStdRec[i].lab1) +
            (.1 * aStdRec[i].lab2) + (.1 * aStdRec[i].lab3) +
            (.25 * aStdRec[i].lab4))/4;
           
            midtermgrade = aStdRc[i].AvgGrade + aStdRec[i].examgrade;
           
            cout << aStdRec[i].RollNo << "\t" << aStdRec[i].AvgGrade
            << aStdRec[i].examgrade << endl;
           
            i++;
    }
}// end option 2

if(option == 3)
{
    float AvgAllGrade1 = 0;
    float AvgAllGrade2 = 0;
    float AvgAllGrade3 = 0;
    float AvgAllGrade4 = 0;
   
while(i <= nTotalRec)
{
        AvgAllGrade1 += aStdRec[i].lab1;
        AvgAllGrade2 += aStdRec[i].lab2;
        AvgAllGrade3 += aStdRec[i].lab3;
        AvgAllGrade4 += aStdRec[i].lab4;
   i++;
}

AvgAllGrade1 /= (nTotalRec + 1);
AvgAllGrade2 /= (nTotalRec + 1);
AvgAllGrade3 /= (nTotalRec + 1);
AvgAllGrade4 /= (nTotalRec + 1);
}// end option 3

if(option == 4)
{
     struct student temp;
     
     for(i = 0; i < nTotalNo; i++)
         {  
           for(j = i + 1; j <= nTotalNo; i++)
           {
                 if(aStdRec[i].RollNo > aStdRec[j].RollNo)
                 {
                 temp = aStdRec[i];
                 aStdRec[i] = aStdRec[j];
                 aStdRec[j] = temp;
                 }
           }
         }
// Print the result

int i = 0;
while(i <= nTotalRec)
{
        cout << aStdRec[i].RollNo << "\t" << aStdRec[i].AvgGrade
        << endl;
       
        i++;
}
}// end option 4

if(option == 5)
{
    struct student temp;
     
     for(i = 0; i < nTotalNo; i++)
         {  
           for(j = i + 1; j <= nTotalNo; i++)
           {
                 if(aStdRec[i].RollNo < aStdRec[j].RollNo)
                 {
                 temp = aStdRec[i];
                 aStdRec[i] = aStdRec[j];
                 aStdRec[j] = temp;
                 }
           }
         }
// Print the result

int i = 0;
while(i <= nTotalRec)
{
        cout << aStdRec[i].RollNo << "\t" << aStdRec[i].AvgGrade
        << endl;
       
        i++;
}
}// end option 5

if(option == 6)
{
    cout << "Which student's greade you want to change? ";
    cin >> SelRollNo;
   
    cout << "Enter his grade: ";
    cin >> NewGrade;
   
    int i = 0;
    while(i <= nTotalRec)
    {
            if(aStdRec[i].RollNo == SelRollNo)
            aStdRec[i].AvgGrade = NewGrade;
           
            i++;
    }
}// end option 6
}// end do

while(option != 7);

cout << "\nQuit" << endl;
output << "\nQuit" << endl;

input.close();
return 0;
}
0
 
itsmeandnobodyelseCommented:
>>>> No this is not homework, this is practice before the test
>>>> Good

Actually, there isn't much difference between 'homework' and 'practice before the test'.

Generally, experts could/should not give full code cause of EE rules if the questioner has not shown own efforts, i. e. has posted at least a rough design how he\she assumes the task could be solved. If an expert gives full code where only the task is given and nothing else, the expert changes the task from designing and coding a program to rebuilding a sample program. As the latter in many cases doesn't demand any code analyzing, it wouldn't give any new knowledge to the questioner. Thus, it is useless regarding 'practice before the test'.

In the sample above, we actually have a C-style program, not using any OO techniques or even C++ syntax. Also, the asker got problems to build the program, not being able to tell what was wrong.

AFabrizi, I would recommend to start again - maybe by analyzing the code you got from Mahesh. You will see, that there are some things you don't need (as the task doesn't require it).

And replace old header files

#include <iostream.h>
#include <conio.h>
#include <iomanip.h>
#include <fstream.h>
#include <stdlib.h>

by C++ standard:

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

Maybe some of your building problems would be gone.

If you still get errors, post us your code and the error message(s). You definitively will get help if you show some efforts of your own.

Regards, Alex



   
0
 
smpoojaryCommented:
Convert it to C++ style like

class Std
{
      ifstream input;
      int i, j, SelRollNo, lab1, lab2, lab3, lab4;
      int option;
      float midtermgrade;
      float nTotalRec, NewGrade, nTotalNo;

      struct student
      {
            long RollNo;
            float lab1;
            float lab2;
            float lab3;
            float lab4;
            float examgrade;
            float AvgGrade;
      } stdRec[1000];


public:
      Std()
      {
            //Initialize variables
      }

      //Create the student database (file with records)
      bool CreateDatabase(); //Return false if unable to create student database

      //How to read from text file and store records into 2d array in c++?
      void ReadStdDatabase();

      //How to calculate and print the grade average and mid term grade for each student?
      void CalGradeAvg(); //Update all records in database(file) also

      //How to calculate and print the average grade of all students for each grade and exam?
      void CalGradeAvgAllStd(); //Update all records in database also

      //How to ask a person which student he/she want to see the record then print the records only what the person is looking for?
      bool GetStdRecord(); //return false if record is not exists

      //How to sort and print the ids and grades in order by ascending id number?
      void SortToAscStdDBase();

      //How to sort and print the ids and grades in order of descending grades?
      void SortToDescStdBase();

      //How to chang the grade for a student?
      bool ChangeGrade();      //Return false if record is not exists
                        //Update modified student record in database
};


int main()
{

      Std stdObj;
      ......          
      stdObj.CreateDatabase();
      ......
      stdObj.ReadStdDatabase();
      ......
      stdObj.CalGradeAvg();
      ......
      stdObj.CalGradeAvgAllStd();
      ......
      stdObj.GetStdRecord();
      ......
      stdObj.SortToAscStdDBase();
      ......
      stdObj.SortToDescStdBase();
      ......
      stdObj.ChangeGrade();      
                        
      return 0;
}

Add i = 0; in the following
.....
i=0;        //Here
while(i <= nTotalRec)
{
        AvgAllGrade1 += aStdRec[i].lab1;
        AvgAllGrade2 += aStdRec[i].lab2;
        AvgAllGrade3 += aStdRec[i].lab3;
        AvgAllGrade4 += aStdRec[i].lab4;
   i++;
}

Try to put code with your own idea. Debug the code. Try to understand where error is occurred and why. Try to solve yourself otherwise ask us.
Wish you all the best
-Mahesh
0
 
waysideCommented:
No comment has been added to this question in more than 21 days, so it is now classified as abandoned.
I will leave the following recommendation for this question in the Cleanup topic area:

Accept: smpoojary

Any objections should be posted here in the next 4 days. After that time, the question will be closed.

wayside
EE Cleanup Volunteer
0
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

All Courses

From novice to tech pro — start learning today.