fork download
  1. // Elaine Torrez CS1A
  2. // _____________________________________________________________
  3. //
  4. // COUNT WORDS IN STRING
  5. // _____________________________________________________________
  6. // This program prompts the user to enter a sentence and then
  7. // determines the number of words in the sentence. A word is
  8. // defined as a sequence of characters separated by spaces.
  9. // _____________________________________________________________
  10. // INPUT
  11. // userStr : The sentence entered by the user
  12. //
  13. // OUTPUT
  14. // words : Number of words in the sentence
  15. // _____________________________________________________________
  16.  
  17. #include <iostream>
  18. using namespace std;
  19.  
  20. // FUNCTION PROTOTYPE
  21. int countWords(const char *str);
  22.  
  23. int main()
  24. {
  25. /****************************************************
  26.   * VARIABLE DECLARATIONS
  27.   ****************************************************/
  28. const int SIZE = 200;
  29. char userStr[SIZE]; // INPUT sentence
  30. int words; // OUTPUT word count
  31.  
  32. /****************************************************
  33.   * INPUT
  34.   ****************************************************/
  35. cout << "Enter a sentence: ";
  36. cin.getline(userStr, SIZE);
  37.  
  38. /****************************************************
  39.   * PROCESS
  40.   ****************************************************/
  41. words = countWords(userStr);
  42.  
  43. /****************************************************
  44.   * OUTPUT
  45.   ****************************************************/
  46. cout << "\nNumber of words: " << words << endl;
  47.  
  48. return 0;
  49. }
  50.  
  51. // *************************************************************
  52. // countWords
  53. // -------------------------------------------------------------
  54. // Returns the number of words in a C-string. Words are counted
  55. // by detecting transitions from spaces to non-space characters.
  56. // *************************************************************
  57. int countWords(const char *str)
  58. {
  59. int count = 0;
  60. bool inWord = false;
  61.  
  62. for (int i = 0; str[i] != '\0'; i++)
  63. {
  64. if (str[i] != ' ' && !inWord)
  65. {
  66. // Starting a new word
  67. inWord = true;
  68. count++;
  69. }
  70. else if (str[i] == ' ')
  71. {
  72. inWord = false;
  73. }
  74. }
  75.  
  76. return count;
  77. }
  78.  
Success #stdin #stdout 0s 5312KB
stdin
Four score and seven years ago
stdout
Enter a sentence: 
Number of words: 6