fork download
  1. // Andres Guzman CSC5 Chapter 10, P. 588, #3
  2. /******************************************************************************
  3.  *
  4.  * DISPLAY ESSAY WORD COUNT
  5.  * ____________________________________________________________________________
  6.  * Program function will accept pointer to a c-string as an argument and will
  7.  * return the number of words typed.
  8.  *
  9.  * Computation:
  10.  *
  11.  * Function will compute using if statements nested inside a for loop
  12.  * ____________________________________________________________________________
  13.  *
  14.  * INPUT
  15.  *
  16.  * SIZE = Array size of characters
  17.  * sentence = Holds entered characters
  18.  *
  19.  * OUTPUT
  20.  *
  21.  * wordcount = total words counted
  22.  *
  23.  ******************************************************************************/
  24. #include <iostream>
  25. #include <cctype>
  26. using namespace std;
  27.  
  28. int words(char *a); //Function Prototype
  29.  
  30. int main()
  31. {
  32. const int SIZE = 1000; //Array Size
  33. char sentence[SIZE]; //Array
  34. cout << "Enter a Sentence: ";
  35. cin.getline(sentence, SIZE); //Allows entire entered line with SIZE limit
  36. //
  37. //Function call inside console output
  38. cout << "\nThere are " << words(sentence)
  39. << " Words in this Sentence." << endl;
  40. }
  41. /*******************************************************************************
  42.  * Adding Definition to function. This function will step through each character
  43.  * of the array and determine whether it is a whitespace character or is a null
  44.  * terminator. If it isn't a whitespace character, it will check whether it is
  45.  * the beginning of the subscript, or if the prior element of the subscript was
  46.  * a whitespace character.
  47.  ******************************************************************************/
  48. int words(char *a)
  49. {
  50. int wordcount = 0; //Accumulator
  51. //
  52. //Initializing for loop to step through subscript array
  53. for (int count = 0; a[count] != '\0'; count++)
  54. {
  55. if(!isspace(a[count]) && (count == 0 || isspace(a[count - 1])))
  56. wordcount++; //Increments if both conditions are true
  57. }
  58. return wordcount; //Returns word count
  59. }
Success #stdin #stdout 0s 544KB
stdin
The if statement checks whether the current character is not a space. If that is true, it then determines whether the current subscript is at the beginning of the string or whether the previous character is a space. If either condition is true, the word counter is incremented since does conditions are true. The loop also makes sure that the null terminator is excluded from processing.
stdout
Enter a Sentence: 
There are 66 Words in this Sentence.