[Okta Webinar] Learn how to a build a cloud-first strategyRegister Now

x
?
Solved

2d array

Posted on 2005-04-27
12
Medium Priority
?
344 Views
Last Modified: 2006-11-18
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?

0
Comment
Question by:AFabrizi
  • 5
  • 2
  • 2
  • +2
11 Comments
 
LVL 32

Expert Comment

by:r-k
ID: 13883130
Is this homework?
0
 
LVL 4

Expert Comment

by:smpoojary
ID: 13883264
>>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
 
LVL 32

Expert Comment

by:r-k
ID: 13883295
smpoojary:

we should avoid doing homework for students, esp. when they have no effort at all on their own.
0
Independent Software Vendors: We Want Your Opinion

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

 
LVL 4

Expert Comment

by:smpoojary
ID: 13883355
Sorry. I didn't think about this.
-Mahesh
0
 

Author Comment

by:AFabrizi
ID: 13884785
No this is not homework, this is practice before the test
0
 
LVL 4

Expert Comment

by:smpoojary
ID: 13884803
Good
0
 

Author Comment

by:AFabrizi
ID: 13885594
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
 
LVL 39

Expert Comment

by:itsmeandnobodyelse
ID: 13887643
>>>> 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
 
LVL 4

Expert Comment

by:smpoojary
ID: 13892140
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
 
LVL 4

Accepted Solution

by:
smpoojary earned 2000 total points
ID: 13893190
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
 
LVL 14

Expert Comment

by:wayside
ID: 15714317
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

Featured Post

[Webinar] Cloud and Mobile-First Strategy

Maybe you’ve fully adopted the cloud since the beginning. Or maybe you started with on-prem resources but are pursuing a “cloud and mobile first” strategy. Getting to that end state has its challenges. Discover how to build out a 100% cloud and mobile IT strategy in this webinar.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Introduction This article is the first in a series of articles about the C/C++ Visual Studio Express debugger.  It provides a quick start guide in using the debugger. Part 2 focuses on additional topics in breakpoints.  Lastly, Part 3 focuses on th…
Basic understanding on "OO- Object Orientation" is needed for designing a logical solution to solve a problem. Basic OOAD is a prerequisite for a coder to ensure that they follow the basic design of OO. This would help developers to understand the b…
The goal of the tutorial is to teach the user how to use functions in C++. The video will cover how to define functions, how to call functions and how to create functions prototypes. Microsoft Visual C++ 2010 Express will be used as a text editor an…
The goal of the video will be to teach the user the concept of local variables and scope. An example of a locally defined variable will be given as well as an explanation of what scope is in C++. The local variable and concept of scope will be relat…
Suggested Courses

872 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question