fork download
  1. #include <iostream>
  2. #include <cstring>
  3. #include <cctype>
  4. using namespace std;
  5.  
  6. int countWords(const char *str, double &avgLetters) {
  7. int words = 0;
  8. int letters = 0;
  9. bool inWord = false;
  10.  
  11. // Iterates through entire string till null terminator
  12. for (int i = 0; str[i] != '\0'; i++) {
  13. // Skips over white spaces
  14. if (isspace(str[i])) {
  15. inWord = false;
  16. // counts the number of words
  17. if (letters > 0) {
  18. words++;
  19. avgLetters += letters;
  20. letters = 0;
  21. }
  22. }
  23. // checks for words
  24. else if (!inWord) {
  25. inWord = true;
  26. }
  27. // Counts letters
  28. letters++;
  29. }
  30.  
  31.  
  32. if (letters > 0) {
  33. words++;
  34. avgLetters += letters;
  35. }
  36.  
  37. return words;
  38. }
  39.  
  40. int main() {
  41. char str[250]; // Character length is 250
  42.  
  43. cout << "Enter a string: ";
  44. cin.getline(str, 250);
  45.  
  46. double avgLetters = 0;
  47. int wordCount = countWords(str, avgLetters);
  48.  
  49. if (wordCount > 0) {
  50. avgLetters /= wordCount;
  51. }
  52.  
  53. cout << "Number of words: " << wordCount << endl;
  54. cout << "Average number of letters in each word: " << avgLetters << endl;
  55.  
  56. return 0;
  57. }
  58.  
Success #stdin #stdout 0.01s 5256KB
stdin
I hope to make it to class today
stdout
Enter a string: Number of words: 8
Average number of letters in each word: 4