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:
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.