Thursday, March 12, 2015

Post #9 - using an array

Today I'll introduce arrays. Arrays are sections of consecutive memory spaces that can hold variables of the same data type in order. They can hold any of the main data types (int, float, double, char, string), and are especially helpful in stepping through strings and sentences (a sentence is basically an array of characters with a \0 at the end, including punctuation and upper/lower chars). When an array is declared, the compiler reserves memory space for the size of the array specified in the brackets [].

int arrayOfIntegers[9];

The array above is named "arrayOfIntegers" (although when naming arrays the same naming style should be used as you name variables and functions, they don't have to be this obvious!). Because the int datatype is used, it only holds integer numbers. The brackets to the right of the array name specify the exact size of the array. However, since an array always counts from 0, arrayOfIntegers actually holds 0-8 integers. (the array counting scheme is from array[0] to array[n - 1], and n is the number of total items held by the array)

Data can be entered into the array via three ways - the array can be initialized when it is declared, the user can enter numbers into the array via a for or while loop, or a data file can be read into the array using <fstream> library.

To initialize the array, put the numbers inside a set of curly braces and assign the set to the array.

int arrayOfIntegers[9] = {21, 55, 42, 93, 76, 12, 39, 68};

A for loop can read user input into the array, using i to "step through" the array until it increments to 9, then the reading loop exits. Another loop displays the filled array on the screen after the user enters 9 numbers into the array.

int array[9];
int userinput;

for(int i = 0; i < 9; i++)
{
cout << "Enter an integer: ";
cin >> array[i];
}

for(int i = 0; i < 9; i++)
{
cout << "Numbers in array: " << array[i] << " ";
}

Data can be read from a file containing data (.txt) into an array, but it's a bit more complicated. It still relies on a while loop to handle the copying of the data file's numbers into the array. A constant integer variable, N, holds the size of the array, since it never changes its value and is not supposed to, it can be declared as a constant variable (no operation can edit its value).

fstream is the more generic version of reading in files. A "data stream object" can be defined using fstream, and this object "substitutes" for the actual text file within the program. Any read/write or open/close operations are performed by member functions affecting the data object; so the data file is not actually "inside" the program, but remains separate. 

Instead of specifying the read operation within the file stream, such as ifstream (to read input from a file) and ofstream (to write output to a file), fstream uses a second parameter after the name of the data file string (*.txt), ios:: __. The __ is replaced with the operation that the fstream object needs to perform, namely in for reading input, out for writing output, or app to append data to the end of a data file.

((Strangely, fstream does not seem to work on my linux computer. I've been sticking with ifstream to read in files, but I'm currently baffled as to how fstream, its supposedly simpler cousin, doesn't want to work correctly.))

const int N = 9;
int array[N];
int numbers = 0;

//Object of the input file stream
ifstream data;

//open the data file
data.open("data.txt");
  if(!data)
  {  cout << "Cannot open file." << endl;
  return 0;
  }
  else
  while(numbers < N && data >> array[numbers])
  { numbers++; }

//close the data file
data.close();

Under data.open, an if/else handles the problem of the data file not existing. If the data object is "false" - if .open failed to find the file in the same directory as the program and returned a 1 to the if statement - then the program outputs a message and exits. Otherwise if the file is found, the while loop immediately reads in data from the input stream object data into the array, as long as the incremented variable numbers does not exceed the size of the array, which is 9.

It's a good idea to close the file as soon as the data has been copied to the program's array. This is done with data.close() which closes the connection that data has with the text file.

In general, if for some reason things aren't outputting correctly within a loop, for instance if the array is outputting wrong numbers, try dropping in a cout << of the variable changed immediately before it to check the output of each statement as the loop continues. This has helped me on several programs where a series of couts led to me discover just where the program had an incorrect operation and, in general, helped me to understand how the program's logic flows as it goes through a loop or complicated statement. After any statements are fixed, then comment out the couts and run it again, if the output is correct, then the extra couts used for debugging can be removed.

No comments:

Post a Comment