fork download
  1. /**************************************************************
  2.  *
  3.  * COUNT THE NUMBER OF WORDS AND FIND AVERAGE NUMBER OF LETTERS
  4.  * ____________________________________________________________
  5.  * This program counts the number of words in a string.The
  6.  * program asks the user to enter a string and then passes
  7.  * it to the function.The function accepts a pointer to
  8.  * a C-string as an argument and returns the number of words
  9.  * in that string. Then, the program uses a second function to
  10.  * calculate the average number of letters.
  11.  * ____________________________________________________________
  12.  * INPUT
  13.  * inWords : The string entered by the user
  14.  *
  15.  * OUTPUT
  16.  * words : Number of words in the string
  17.  **************************************************************/
  18. #include <iostream>
  19. #include <cstring>
  20. #include <string>
  21. #include <iomanip>
  22. using namespace std;
  23.  
  24. //Prototype for functions
  25. int CountWords(char* string);
  26.  
  27. int CountLetters(char* string);
  28.  
  29. int main()
  30. {
  31. //Declare variables
  32. int SIZE = 50; // Holds size of the array
  33. char inWords[SIZE]; // Input - String of characters entered by user
  34. int words; // Output - Number of words in string
  35. double average; // Output - Average number of letters
  36. int Letters; // Holds number of letters
  37.  
  38. //Prompt user for input
  39. cout << "Enter a string of characters." << endl;
  40. cin.getline(inWords, SIZE);
  41.  
  42. //Call on functions CountWords and CalcAverage
  43. words = CountWords(inWords);
  44. words += 1;
  45. Letters = CountLetters(inWords);
  46.  
  47. //Calculate average
  48. average = Letters / words;
  49.  
  50. //Display number of words and average
  51. cout << "The number of words in this string is: " << words << endl;
  52. cout << fixed << setprecision(2);
  53. cout << "The average number of letters is: " << average;
  54. return 0;
  55. }
  56.  
  57. //Define function CountWords
  58. int CountWords(char *string)
  59. {
  60. int count = 0; // Counter for loop
  61. int length; // Holds the number of words in the string
  62.  
  63. while(string[count] != '\0')
  64. {
  65. if(string[count] == ' ')
  66. {
  67. length++;
  68. }
  69. count++;
  70. }
  71. return length;
  72. }
  73.  
  74. // Define function CalcAverage
  75. int CountLetters(char *string2)
  76. {
  77. int letters = 0;
  78. int count = 0;
  79.  
  80. while(string2[count] != '\0')
  81. {
  82. if(string2[count] != ' ')
  83. {
  84. letters++;
  85. }
  86. else if(string2[count] == ' ')
  87. {
  88. letters--;
  89. }
  90. count++;
  91. }
  92. return letters;
  93. }
Success #stdin #stdout 0s 15240KB
stdin
Standard input is empty
stdout
Enter a string of characters.
The number of words in this string is: 1
The average number of letters is: 0.00