C++/C array

Advertisement


Question
I am writing a program to read a file containing student names and scores for 3 exams. First of all I need to find the highest score for each exam and calculate the cut-off grades, which are 90% of the top score(A), 80% of the top score(B), 70% of the top score(C) and 60% of the top score(D). I am required to use parallel one dimensional arrays. I will improve the design later. For now I just want to search the input file for the highest score for Exam 1, 2, 3 and print them out(just to test)..What I am doing wrong?..Thanks a lot for the help in the past.


//Sample Program 12- A non-interactive program to calculate student grades.
//**************************************************************************************

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

const int SIZE=20;

int main()
{
  int exam1Array[SIZE];
  int exam2Array[SIZE];
  int exam3Array[SIZE];
  int highScore;
  int count=0;
  string name[SIZE];
   ifstream inFile;

  inFile.open("grades.dat");
     if(!inFile)
     {
        cout<<"Unable to open input file, program abnormally ended";
        return 1;
     }

       inFile>>name[count]>>exam1Array[count]>>exam2Array[count]>>exam3Array[count];
     highScore=0;
     for(count=0; count<SIZE; count++)

        if(array[count]>highScore)
         highScore=array[count];
        

        cout<<highScore<<endl;
        return 0;
}  

Answer
Well you can now define arrays and open a file associated with a file stream and check that it is opened.

I take it you have up to SIZE sets of student exam result data in the file grades.dat arranged something like:

Student0 20 40 50
Student1 30 40 70
      .
      .
      .
Student19 33 44 55

Now what you have not done is use your brain and checked what your code actually does. Sorry to be a little blunt but you do have to think and you do have to be able to see what you have actually asked the computer to do rather than what you thought you had asked it to do.

I am going to lead you through the process of looking at your code and checking it does what it should in the hope that you will get the idea and be able to do this for yourself in future. At times you may feel I am being a bit silly and childish and rubbing the point in. You may well be correct but as you seem not to be able to apply this knowledge hopefully this will help reinforce the points(s).

To start with review this line:

   inFile >> name[count]
         >> exam1Array[count]
         >> exam2Array[count]
         >> exam3Array[count];

I have wrapped it around a bit and spaced it out.

As far as I can tell this is your code to read all the data sets from the data file.

Look at it. Match it to my statement above it on what I think you have in grades.dat. Will the code you supply for reading all data set values read all data set values? If you think the answer is yes then I think you need to go right bad to basics again.

If you have many sets of things to process how would we do it? Process here includes reading and writing data to/from files and the user, performing calculations on the sets of data, etc. To put it another way if we wish to do something repeatedly how would we do it?

Yes we would use a loop.

Does your code to repeatedly input sets of data contain a loop? No.

That is your main problem.

OK, so we need a loop. What sort of loop would be best? Well we need to keep a record of the current index, and we need to increment this value and we need to keep doing this while one or more conditions are true. This seems to fit a good old for loop. The loop variable is count, which is already initialised to zero so we have no initial expression. We need to determine the conditions to keep looping and we need to increment count as the third for loop expression:

   for ( /*no initial expression*/; /* condition */; ++count )
   {
       inFile >> name[count]
         >> exam1Array[count]
         >> exam2Array[count]
         >> exam3Array[count];
   }

So under what conditions should we keep reading values? Well I would suggest while we still have space in the arrays (count < SIZE) and while the end of file has not been reached and the stream has not had any other errors, i.e. while the stream is good:

   for ( ; count<SIZE && inFile.good(); ++count )
   {
       inFile >> name[count]
         >> exam1Array[count]
         >> exam2Array[count]
         >> exam3Array[count];
   }

After terminating the loop we do not know why it finished. The two conditions are: we have read as many values as possible OK in which case the stream is good or at the end of file (eof); or there was some problem reading the data, in which case the stream will be bad or fail. The fail() stream function returns true if the stream has failed or is bad. Fail is a recoverable error, generally a data formatting error, and bad is a fatal error.

   if ( inFile.fail() )
   {
       cout << "Error reading data, program abnormally ended\n";
       return 2;
   }

Now we come to your code to process the read data:

   for(count=0; count<SIZE; count++)
       if(array[count]>highScore)
         highScore=array[count];
        
       cout<<highScore<<endl;
       return 0;


You might be wondering what is wrong with this code and why I have included the two lines that are not part of the loop and indented them as if they were.

The reason is that this is what the code looked like to me after posting through AllExperts and being emailed to me. I had to read the code carefully to check what you were actually doing. You have incorrectly indented the code for these two lines, and you do not use { and } where you do not have to which makes it even more difficult to see what was intended. Did you mean:


   for(count=0; count<SIZE; count++)
   {
       if(array[count]>highScore)
         highScore=array[count];
        
       cout<<highScore<<endl;
       return 0;
   }

And you forgot the { and }, or did you mean:

   for(count=0; count<SIZE; count++)
       if(array[count]>highScore)
         highScore=array[count];
        
   cout<<highScore<<endl;
   return 0;

Which is most likely the case, or maybe:

   for(count=0; count<SIZE; count++)
   {
       if(array[count]>highScore)
         highScore=array[count];
        
       cout<<highScore<<endl;
   }
   return 0;

Which reasonable if you are trying to see how the highscore value changes.

You also tend not to space your code out much and use long lines. Try to space your code out. Pay attention to indentation and do not use very long lines some of your lines had been wrapped by the time they got to me.

Why do all this? The compiler does not care. I care. You will care when your code gets complex and you go back to something you wrote a while ago and try to understand it.

Make your code as easy for people to read and understand as possible. My immediate reaction to badly formatted code is not to go anywhere near it. My second is to re-format it. In future I shall reject any of your questions that you cannot be bothered to ensure are laid out neatly.

One final warning: tabs are easy to use for indentation. But they have a problem. Different editors and viewers and printers use different spacing values for tabs. VC++ uses 4 spaces by default, other editors use 8 or 5, word processors use length spacings for tabs which can be changed. All these conspire to mean your code may not look the same in different editors. This is especially true if you mix spaces and tabs, the indentation will get messed up. This is why I look for an option that converts tabs to spaces (if 1 tab = 3 spaces then up to 3 space characters will be inserted for a tab instead of a tab character).

Now what are you doing in this loop? Well the part that collects the highscore is good other than the fact you have no object called array (you have exam1Array etc.). This is a compiler error and you should have been able to fix this yourself, it is obvious enough after all.

The thing that is wrong are the expressions to the for-loop. You assume you have exactly SIZE data sets. I think you have up to SIZE data sets. You have the number of data sets in count from the (now added) dataset reading loop. So you need to iterate from 0 to count-1, not 0 to SIZE-1. You can do this like so:

   for ( int i=0; i < count; ++i )

And use [i] not [count].

Of course you really need to calculate three high scores: one for each exam array, however I would get you program working with 1 array first.


I am going to suggest a way to develop your code that I hope will help ensure you have a greater degree of success.

The idea is to tackle the problem incrementally. At each stage you have something that builds and runs and the program does what it is supposed to for that stage.

For example you could start by defining your arrays, compiling and building the program. Running the program should produce no visible results but shows the build process works. Best to ensure this is OK from the start.

Next open the file with the error checking. Run the program (with no file). It should print the error message and terminate OK. Now create the file and ensure the program runs and opens it OK (no error message).

Next add the code to read the values from the file into the arrays. Add some code to display the read values (repetition again think loop) and the count of read data sets. Again get this working. Try with no data in the file, one data set, SIZE-1 data sets, SIZE data sets, SIZE+1 data sets and some badly formed data sets (e.g. remove one value from the end of a line) to ensure the error checking works.

Now add the code to calculate the high scores. Get this working and test it. Remember you have three sets of exam questions.

And yes this is a real method of developing software. Of course the stages may be larger for more experienced developers, but that come with time and practice.

Before posting another question try reading though all my answers and see if any of the points made in them could apply to your problem. I will be less likely to accept questions having similar failings to those you seem to keep making as I have already tried to explain these things to you and so would have little more to say.  

C++

All Answers


Answers by Expert:


Ask Experts

Volunteer


Ralph McArdell

Expertise

I am a software developer with more than 15 years C++ experience and over 25 years experience developing a wide variety of applications for Windows NT/2000/XP, UNIX, Linux and other platforms. I can help with basic to advanced C++, C (although I do not write just-C much if at all these days so maybe ask in the C section about purely C matters), software development and many platform specific and system development problems.

Experience

My career started in the mid 1980s working as a batch process operator for the now defunct Inner London Education Authority, working on Prime mini computers. I then moved into the role of Programmer / Analyst, also on the Primes, then into technical support and finally into the micro computing section, using a variety of 16 and 8 bit machines. Following the demise of the ILEA I worked for a small company, now gone, called Hodos. I worked on a part task train simulator using C and the Intel DVI (Digital Video Interactive) - the hardware based predecessor to Indeo. Other projects included a CGI based train simulator (different goals to the first), and various other projects in C and Visual Basic (er, version 1 that is). When Hodos went into receivership I went freelance and finally managed to start working in C++. I initially had contracts working on train simulators (surprise) and multimedia - I worked on many of the Dorling Kindersley CD-ROM titles and wrote the screensaver games for the Wallace and Gromit Cracking Animator CD. My more recent contracts have been more traditionally IT based, working predominately in C++ on MS Windows NT, 2000. XP, Linux and UN*X. These projects have had wide ranging additional skill sets including system analysis and design, databases and SQL in various guises, C#, client server and remoting, cross porting applications between platforms and various client development processes. I have an interest in the development of the C++ core language and libraries and try to keep up with at least some of the papers on the ISO C++ Standard Committee site at http://www.open-std.org/jtc1/sc22/wg21/.

Education/Credentials

©2016 About.com. All rights reserved.