fork download
  1. //Cecilia Rangel CSC5 Chapter 10, P.588, #3
  2. //
  3. /**************************************************************
  4.  *
  5.  * COMPUTE WORD COUNTER
  6.  * ____________________________________________________________
  7.  * This program returns an integer and accepts a
  8.  * pointer to a C-string as an arguement and returns the
  9.  * number of words contained in the string.
  10.  *_____________________________________________________________
  11.  * INPUT
  12.  * userinput : INPUT a string from the user
  13.  *
  14.  * OUTPUT
  15.  * words : OUTPUT the amount of words in the string
  16.  *
  17.  * ***************************************************************/
  18.  
  19. #include <iostream>
  20. #include <iomanip>
  21. using namespace std;
  22.  
  23. int CountNumWords(char* ptr);
  24.  
  25. int main()
  26. {
  27. //
  28. //Declare variables and pointers
  29. int SIZE = 100; //Initialize size to 100
  30. char userInput[SIZE]; //User input
  31. char* ptr; //Pointer to character type
  32. ptr = userInput; //Assign pointer to array
  33. int numWords; //Number of words
  34. //
  35. //Prompt user to enter character string
  36. cout << "Enter a character string.\n";
  37. cin.getline(userInput, SIZE);
  38. //
  39. //Call to function
  40. numWords = CountNumWords(ptr);
  41. //
  42. //Output the number of words in string
  43. cout << "The number of words in your string is ";
  44. cout << numWords;
  45. return 0;
  46. }
  47. //
  48. //Return number of words
  49. int CountNumWords(char* ptr)
  50. {
  51. int count;
  52. int size = 0;
  53. int numWords = 0;
  54. //
  55. //Find size of string
  56. for (count = 0; *(ptr + count) != '\0'; count++)
  57. size++;
  58. //
  59. //Find number of words
  60. for (count = 0; count <= size; count++)
  61. {
  62. if (*(ptr + count) == ' ' || *(ptr + count) == '\0')
  63. numWords++;
  64. }
  65. return numWords;
  66. }
Success #stdin #stdout 0s 544KB
stdin
i'm living la vida loca
stdout
Enter a character string.
The number of words in your string is 5