Thursday, March 12, 2015

Post #7 - arrays and sentences

I realized that I had skipped number 7 in the post count...
Here's an example of a sentence array (to continue from post #9).


In this snippet, the array holding the sentence is not actually defined - because the sentence is actually an array of characters in itself. When the user enters a sentence, getline() stores the sentence into a string of characters and spaces. This by itself is not an array though, because to work with it the size of the array needs to be found. The .length() member function for strings can be used for this purpose, the length of the sentence string becomes the length of the character array. As getline() includes the \n from the user's [Enter] input, 1 must be subtracted to avoid having .length() count that extra character as part of the sentence. Now that we have the size of the sentence in characters, we can use a while loop with an increment integer or a for loop to step through the sentence and keep track of how many uppercase, lowercase and vowels are in the sentence for the user. The first two rely on two functions from <cctype> library to check for upper or lower case characters. Note that sentence, while treated as a string for the user to initialize before the while loop, is now treated as a character array within the loop simply by including the increment variable in brackets after the string name. Now sentence is called as sentence[check] and each character of the string is checked for each of the three conditions. Once one of them has been met or none of them match (i.e. the sentence has a space at that position), the check increments and goes to the next character in the sentence.

No comments:

Post a Comment