fork download
  1. //Zachary Abdollahi CS1A Chapter 10, P. 588, #3
  2. /*******************************************************************************
  3. *
  4. * COUNT WORDS IN STRING
  5. *_______________________________________________________________________________
  6. * This program accepts a C-string from the user, passes a
  7. * pointer to the C-string to a function that counts the number
  8. * of words contained in the string, and displays the word count.
  9. *_______________________________________________________________________________
  10. * INPUT
  11. * userString : C-string entered by the user
  12. *
  13. * OUTPUT
  14. * wordCount : Number of words contained in the C-string
  15. *
  16. *******************************************************************************/
  17.  
  18. #include <iostream>
  19. #include <cctype>
  20. using namespace std;
  21.  
  22. // Function Prototype
  23. int countWords(const char *strPtr);
  24.  
  25. int main ()
  26. {
  27. const int SIZE = 200; // Maximum C-string size
  28. char userString[SIZE]; //INPUT
  29. int wordCount; //OUTPUT
  30.  
  31. // Input String
  32. cout << "Enter a string: ";
  33. cin.getline(userString, SIZE);
  34.  
  35. // Compute Word Count
  36. wordCount = countWords(userString);
  37.  
  38. // Output Result
  39. cout << "The string contains " << wordCount << " words." << endl;
  40.  
  41. return 0;
  42. }
  43.  
  44. /*******************************************************************************
  45. *
  46. * FUNCTION countWords
  47. *_______________________________________________________________________________
  48. * This function accepts a pointer to a C-string, counts the
  49. * number of words separated by whitespace characters, and
  50. * returns the total word count as an integer.
  51. *_______________________________________________________________________________
  52. * INPUT
  53. * strPtr : Pointer to a null-terminated C-string
  54. *
  55. * OUTPUT
  56. * words : Integer count of words in the C-string
  57. *
  58. *******************************************************************************/
  59. int countWords(const char *strPtr)
  60. {
  61. int words = 0; //OUTPUT
  62. bool inWord = false; // Flag to track if currently inside a word
  63.  
  64. while (*strPtr != '\0')
  65. {
  66. if (isspace(*strPtr))
  67. {
  68. inWord = false;
  69. }
  70. else if (!inWord)
  71. {
  72. inWord = true;
  73. words++;
  74. }
  75.  
  76. strPtr++;
  77. }
  78.  
  79. return words;
  80. }
Success #stdin #stdout 0s 544KB
stdin
Four score and seven years ago
stdout
Enter a string: The string contains 6 words.