fork download
  1. //Devin Scheu CS1A Chapter 10, P. 588, #3
  2. //
  3. /**************************************************************
  4. *
  5. * COUNT NUMBER OF WORDS IN C-STRING
  6. * ____________________________________________________________
  7. * This program determines the number of words in a C-string.
  8. * ____________________________________________________________
  9. * INPUT
  10. * inputString : The C-string entered by the user
  11. *
  12. * OUTPUT
  13. * wordCount : The number of words in the string
  14. *
  15. **************************************************************/
  16.  
  17. #include <iostream>
  18. #include <iomanip>
  19.  
  20. using namespace std;
  21.  
  22. // Function to count words using pointer notation
  23. int countWords(const char* str) {
  24. const char* ptr = str;
  25. int wordCount = 0;
  26. bool inWord = false;
  27.  
  28. while (*ptr != '\0') {
  29. if (*ptr == ' ' || *ptr == '\t' || *ptr == '\n') {
  30. inWord = false;
  31. } else if (!inWord) {
  32. inWord = true;
  33. wordCount++;
  34. }
  35. ptr++;
  36. }
  37. return (wordCount > 0) ? wordCount : 0;
  38. }
  39.  
  40. int main () {
  41.  
  42. //Variable Declarations
  43. const int MAX_SIZE = 100; //OUTPUT - Maximum size of the input string
  44. char inputString[MAX_SIZE]; //INPUT - The C-string entered by the user
  45. int wordCount; //OUTPUT - The number of words in the string
  46.  
  47. //Prompt for Input and Echo
  48. cout << "Enter a string (max 99 characters): ";
  49. cin.getline(inputString, MAX_SIZE);
  50. cout << inputString << endl;
  51.  
  52. //Calculate Word Count
  53. wordCount = countWords(inputString);
  54.  
  55. //Separator and Output Section
  56. cout << "-------------------------------------------------------" << endl;
  57. cout << "OUTPUT:" << endl;
  58.  
  59. //Output Result
  60. cout << left << setw(25) << "Word Count:" << right << setw(15) << wordCount << endl;
  61.  
  62. } //end of main()
Success #stdin #stdout 0.01s 5320KB
stdin
I want to go to the gym on friday
stdout
Enter a string (max 99 characters): I want to go to the gym on friday
-------------------------------------------------------
OUTPUT:
Word Count:                            9