>>Go over the string and count spaces
Generally, yes, but you also have to check if words are separated by more than one white space (spaces or tabs). When a white space character is encountered you have to increment the loop counter until the first non-white space character or end-of-string is found before continuing the loop. If you don't, the word count might be wrong.
int wordCount( char *line )
int count = 0 ;
// advance until the first nonwhitespace character
while( isspace( *line ) ) line++ ;
int len = strlen( line ) ;
bool onWord = true ;
for( int i = 0 ; i < len; i++ )
if( isspace( line[i] ) )
// INcrement count only when
// stepping OFF word to whitespace
if( onWord )
onWord = false ;
onWord = true ;
// If you ended while still on word
// then increment count here to count
// the "last" word
if( onWord )
return count ;
char *line1 = "a line of words" ;
char *line2 = "Hi ther e !! Each glob of characters\n"
"counts as a word \t \t \t \n" ;
char *line3 = "Here's another long line of 3 4 6 6 8 " ;
printf( "%d words in `%s`\n\n", wordCount(line1), line1 ) ;
printf( "%d words in `%s`\n\n", wordCount(line2), line2 ) ;
printf( "%d words in `%s`\n\n", wordCount(line3), line3 ) ;
int i, j, count = 0, end = 0, line = 0, word = 0, flag = 0;
printf ( "Enter the strings\n" );
gets ( name );
for ( i = 0; name[i] != '\0'; i++ )
if ( name[i] == ' ' || name[i] == '\t' )
printf ( " " );
if ( name[i] == '\0' )
end = 0;
else if ( end == 0 )
end = 1;
if ( name[i] == ' ' || name[i] == '\t' || name[i] == '\n' )
flag = 0;
else if ( flag == 0 )
flag = 1;
printf ( "Total number of characters %d\n", count );
printf ( "Total number of word %d\n", word );
printf ( "Total number of line %d\n", line );
Edited 6 Years Ago by __avd: Added [code] tags. For easy readability, always wrap programming code within posts in [code] (code blocks).
Write a C program that should create a 10 element array of random integers (0 to 9). The program should total all of the numbers in the odd positions of the array and compare them with the total of the numbers in the even positions of the array and indicate ...
I have a 2d matrix with dimension (3, n) called A, I want to calculate the normalization and cross product of two arrays (b,z) (see the code please) for each column (for the first column, then the second one and so on).
the function that I created to find the ...