fork download
  1. //Charlotte Davies-Kiernan CS1A Chapter 10 P. 589 #4
  2. //
  3. /******************************************************************************
  4.  *
  5.  * Compute Word Average
  6.  * ____________________________________________________________________________
  7.  * This program will accept a sentence from the user and return the number of
  8.  * words and letters within it and then the average letters per word.
  9.  *
  10.  * Formula used:
  11.  * average = (letterCount * 1.0) / wordCount
  12.  * ____________________________________________________________________________
  13.  * Input
  14.  * SIZE :Word limit for the input
  15.  * cstringInput :Cstring version of input
  16.  *
  17.  * Output
  18.  * wordCount :Amount of words in the c-string
  19.  * letterCount :Amount of letters in the string
  20.  * averageLetters :Average amount of letters per word
  21.  *****************************************************************************/
  22. #include <iostream>
  23. #include <cstring>
  24. #include <iomanip>
  25. using namespace std;
  26.  
  27. //Function Prototypes
  28. int countWords(const char *cstr);
  29. int countLetters(const char *cstr);
  30.  
  31. int main() {
  32. //Data Dictionary
  33. const int SIZE = 200;
  34. char cstringInput[SIZE];
  35. int wordCount;
  36. int letterCount;
  37. float averageLetters;
  38.  
  39. //Prompt User
  40. cout << "Enter a sentence: " << endl;
  41. cin.getline(cstringInput, SIZE);
  42.  
  43. //Count Words and Letters
  44. wordCount = countWords(cstringInput);
  45. letterCount = countLetters(cstringInput);
  46.  
  47. //Compute Average
  48. if(wordCount > 0)
  49. averageLetters = ((letterCount) * 1.0) / wordCount;
  50. else
  51. averageLetters = 0;
  52.  
  53. //Display!
  54. cout << fixed << setprecision(2);
  55. cout << "Word count: " << wordCount << endl;
  56. cout << "Total letters: " << letterCount << endl;
  57. cout << "Average letters per word: " << averageLetters << endl;
  58.  
  59. return 0;
  60. }
  61. //Function Definitions
  62. int countWords(const char *cstr) {
  63. int count = 0;
  64. bool inWord = false;
  65. for(int i = 0; cstr[i] != '\0'; i++) {
  66. if(!isspace(cstr[i])){
  67. if(!inWord){
  68. count++;
  69. inWord = true;
  70. }
  71. } else {
  72. inWord = false;
  73. }
  74. }
  75. return count;
  76. }
  77.  
  78. int countLetters(const char *cstr) {
  79. int letterCount = 0;
  80. for(int i = 0; cstr[i] != '\0'; i++){
  81. if(isalpha(cstr[i])){
  82. letterCount++;
  83. }
  84. }
  85. return letterCount;
  86. }
Success #stdin #stdout 0.01s 5304KB
stdin
Georgie is the name of my cat
stdout
Enter a sentence: 
Word count: 7
Total letters: 23
Average letters per word: 3.29