Making my way through my first C Programming book and I have a solid understanding of the purpose and result of every line in the code with the exception of this section:
Code:
Line 1. while ( *line != kZeroByte ) {
Line 2. if ( ! isspace( *line ) ) {
Line 3. if ( ! inWord ) {
Line 4. numWords++;
Line 5. inWord = true;
}
}
else
inWord = false;
}
from this word count code:
Code:
#include <stdio.h>
#include <ctype.h>
#include <stdbool.h>
#define kMaxLineLength 200
#define kZeroByte 0
void ReadLine( char *line );
int CountWords( char *line );
int main (int argc, const char * argv[]) {
char line[ kMaxLineLength ];
int numWords;
printf( "Type a line of text, please:\n" );
ReadLine( line );
numWords = CountWords( line );
printf( "\n---- This line has %d word", numWords );
if ( numWords != 1 )
printf( "s" );
printf( " ----\n%s\n", line );
return 0;
}
void ReadLine( char *line ) {
int numCharsRead = 0;
while ( (*line = getchar()) != '\n' ) {
line++;
if ( ++numCharsRead >= kMaxLineLength-1 )
break;
}
*line = kZeroByte;
}
int CountWords( char *line ) {
int numWords, inWord;
numWords = 0;
inWord = false;
while ( *line != kZeroByte ) {
if ( ! isspace( *line ) ) {
if ( ! inWord ) {
numWords++;
inWord = true;
}
}
else
inWord = false;
line++; //increments the line array to the next character to start the loop again.
}
return numWords;
}
Here is my confusion. As I read the section of code that is confusing me I would guess that numWords++ would increment the number of characters in the string and not the number of words. Here is my plain english translation:
Code:
Line 1. while the value of line[x] is not equal to zero
Line 2. if the value of line[x] is not 'white-space'
Line 3. if the previous if statement is true
Line 4. increment numWords;
Line 5. change inWord from false to true;
with x = to the position in the char position in the line array
Now, I feel like I have a solid understand of pointers, arrays, and increments but for the life of me, I cannot figure out why 'numWords++' increments the word count.
If I am cycling through each line[x] and if it is not a 'white-space' character, i will increment numWords, why does that not count the characters.
Example:
Line[array] |
1 |
2 |
3 |
4 |
5 |
6 |
7 |
8 |
9 |
10 |
11 |
12 |
13 |
14 |
15 |
char value |
I |
N |
|
G |
O |
D |
|
W |
E |
|
T |
R |
U |
S |
T |
numWords = 0
the value of line[1] is not equal to zero
the value of line[1] is not 'white-space' (TRUE)
Since the previous if value is TRUE
increment numWords;
change inWord from false to true;
numWords now equals 1
The value of line[2] is not equal to zero
the value of line[2] is not 'white-space' (TRUE)
since the previous if value is TRUE
increment numWords;
change inWord from false to true;
numWords now equals 2
Someone please give me some hints as to where my logic is taking the hit.
Thanks, Sean