Console Input and Output with Arrays

Writing the values from an array to the console is straight-forward. Consider the previous example with the addition of the variable numScores:

const int NUM_STUDENTS = 100; int scores[NUM_STUDENTS] = { 0 }; int numScores = 0; numScores will be used to store the number of scores that are actually in the array. We can assume that after reading the student scores into the array, numScores is in the range 0 to NUM_STUDENTS. We can write the scores to the console using a simple for loop: for (int i = 0; i < numScores; i++) cout << scores[i] << endl;

Reading data from the keyboard is a little more involved. We have to read a data item, save it in the next available array element, and keep track of how many items we have read so that we do not write beyond the end of the array. Also, there has to be some way for the users to indicate that they are done entering data; for example, entering a negative score could signal that there is no more data to enter. The following code fragment demonstrates reading integer values from the keyboard and storing them in the scores[] array:

  const int NUM_STUDENTS = 100;       // maximum number of scores
  int scores[NUM_STUDENTS] = { 0 };   // array to hold scores
  int numScores = 0;                  // actual number of scores
  int inputValue;                     // temporary input value

  cout << "Enter a score (-1 when done): ";  // prompt for input
  cin >> inputValue;                         // read from keyboard

  while ( inputValue >= 0 && numScores < NUM_STUDENTS) {
     scores[numScores] = inputValue;
     numScores++;

     cout << "Enter a score (-1 when done): ";  // prompt for input
     cin >> inputValue;                         // read from keyboard
  }
It is easy for a user to "break" this code. The extraction operator (>>) performs basic input parsing, but if the user enters a value that can not be parsed as an integer (say, a decimal number or string), then the results are unpredictable. We will only use this method of console input for very simple programs.