fork download
  1. /*******************************************************************************
  2.  * Aiden Stannard // CS1A // Chapter 10 Homework: Challange 3# // 11/28/2026
  3.  * _____________________________________________________________________________
  4.  *
  5.  * Word Counter
  6.  * _____________________________________________________________________________
  7.  *
  8.  * This program recieves a string of words and outpts the number of words in
  9.  * that string
  10.  * _____________________________________________________________________________
  11.  *
  12.  * Input:Enter a string:___
  13.  *
  14.  * Output: Word count:___
  15.  ******************************************************************************/
  16. #include <iostream>
  17. #include <cctype>
  18. #include <cstring>
  19.  
  20. using namespace std;
  21.  
  22. int countWords(const char *); // word counter function prototype
  23.  
  24. int main() {
  25. char input[256]; //
  26.  
  27. cout << "Enter a string: ";
  28. cin.getline(input, 256);
  29. /* insures that the entire input is assigned to "input" when the user enters
  30.   a space bar between different words*/
  31.  
  32. cout << "Word count: " << countWords(input) << endl;
  33. // Passes user input to function
  34. return 0;
  35. }
  36.  
  37. int countWords(const char* str) {
  38. int count = 0;
  39. bool inWord = false; // initialized bool value to a safe false value
  40.  
  41. while (*str != '\0') { // loop stop iterating if str becomes equal to a null
  42. if (isspace(*str)) // determines if
  43. {
  44. inWord = false;
  45. }
  46. else if (!inWord)
  47. {
  48. inWord = true;
  49. count++;
  50. }
  51. str++;
  52. }
  53. return count;
  54. }
Success #stdin #stdout 0s 544KB
stdin
what is your name

stdout
Enter a string: Word count: 9