fork download
  1. //Sam Trivikraman CS1A Chapter 10, p. 589, #4
  2. //
  3. /*
  4.  ******************************************************************************
  5. Count The Number of Words In A String (#3 Modified)
  6. _______________________________________________________________________________
  7. This program counts and displays the number of words and average number
  8. of letters in a string.
  9. _______________________________________________________________________________
  10. INPUT
  11. the string of words : The sentences contained within a cstring.
  12. number of words : The number of words in the string.
  13.  
  14. OUTPUT
  15. average letters : The average number of letters per word
  16. _______________________________________________________________________________
  17. *******************************************************************************
  18. */
  19.  
  20. #include <iostream>
  21. #include <cstring>
  22. #include <cctype>
  23. using namespace std;
  24.  
  25. //Function that calculates the average number of letters per word
  26. int counter (char sentence[])
  27. {
  28. int numLetters; //INPUT The number of letters in the string
  29. int numWords; //INPUT The number of words in the string
  30. int avg; //OUTPUT The average number of letters in the string
  31.  
  32. //Calculate the number of words and letters in the string
  33. for(int i = 0; i < 100; i++)
  34. {
  35. if(isalpha(sentence[i]))
  36. {
  37. numLetters++;
  38. }
  39.  
  40. if(isspace(sentence[i]))
  41. {
  42. numWords++;
  43. }
  44. }
  45.  
  46. numWords++;
  47. //Calculate the average letters per word
  48. avg = numLetters / numWords;
  49. //return the average letters per word
  50. return avg;
  51. }
  52.  
  53. int main() {
  54.  
  55. char words[100]; //INPUT The sentences contained within a cstring
  56.  
  57. //Ask the user for a string of words
  58. cout << "Please enter a string: " << endl;
  59. cin >> words;
  60. //Output the average letters per word
  61. cout << "The average number of letters per word is: " << counter(words) << endl;
  62. return 0;
  63. }
  64.  
Success #stdin #stdout 0.01s 5300KB
stdin
hello my name is
stdout
Please enter a string: 
The average number of letters per word is: 0