fork download
  1.  
  2. //Dione Torrevillas CS1A Chapter 10, P. 588, #3
  3. /******************************************************************************
  4.  * WORD COUNTER
  5.  * This program counts the number of words contained in
  6.  * a C-string entered by the user.
  7.  *
  8.  * INPUT:
  9.  * str : String entered by the user
  10.  *
  11.  * OUTPUT:
  12.  * words : Number of words in the string
  13.  ******************************************************************************/
  14. #include <iostream>
  15. #include <cctype>
  16. using namespace std;
  17.  
  18. // Function prototype
  19. int wordCounter(char *str);
  20.  
  21. int main()
  22. {
  23. const int SIZE = 200;
  24. char str[SIZE];
  25.  
  26. // Get a string from the user.
  27. cout << "Enter a string: ";
  28. cin.getline(str, SIZE);
  29.  
  30. // Display the number of words.
  31. cout << "Number of words: " << wordCounter(str) << endl;
  32.  
  33. return 0;
  34. }
  35.  
  36. // Count the words in the C-string.
  37. int wordCounter(char *str)
  38. {
  39. int words = 0;
  40. bool inWord = false;
  41.  
  42. for (int count = 0; str[count] != '\0'; count++)
  43. {
  44. // A space marks the end of a word.
  45. if (isspace(static_cast<unsigned char>(str[count])))
  46. inWord = false;
  47. else if (!inWord)
  48. {
  49. // Count the beginning of a new word.
  50. words++;
  51. inWord = true;
  52. }
  53. }
  54.  
  55. return words;
  56. }
  57.  
Success #stdin #stdout 0s 544KB
stdin
Four score and seven years ago
stdout
Enter a string: Number of words: 6