fork download
  1. //Charlotte Davies-Kiernan CS1A Chapter 10 P. 588 #3
  2. //
  3. /******************************************************************************
  4.  *
  5.  * Compute Word Counter
  6.  * ____________________________________________________________________________
  7.  * This program will accept a sentence from the user and return the number of
  8.  * words within it.
  9.  * ____________________________________________________________________________
  10.  * Input
  11.  * SIZE :Word limit for the input
  12.  * cstringInput :Cstring version of input
  13.  * strInput :string version of input
  14.  *
  15.  * Output
  16.  * wordCountCStr :Amount of words in the c-string
  17.  * wordCountString :Amount of words in the string.
  18.  *****************************************************************************/
  19. #include <iostream>
  20. #include <cstring>
  21. #include <iomanip>
  22. using namespace std;
  23.  
  24. //Function Prototypes
  25. int countWords(const char *cstr);
  26. int countWords(const string &str);
  27.  
  28. int main() {
  29. //Data Dictionary
  30. const int SIZE = 200;
  31. char cstringInput[SIZE];
  32. int wordCountCStr;
  33. string strInput;
  34. int wordCountString;
  35.  
  36. //Prompt User
  37. cout << "Enter a sentence: " << endl;
  38. cin.getline(cstringInput, SIZE);
  39.  
  40. //Count Words
  41. wordCountCStr = countWords(cstringInput);
  42. strInput = string(cstringInput);
  43. wordCountString = countWords(strInput);
  44.  
  45. //Display!
  46. cout << "Word count (c-string version): " << wordCountCStr << endl;
  47. cout << "Word count (string version): " << wordCountString << endl;
  48.  
  49. return 0;
  50. }
  51. //Function Definitions
  52. int countWords(const char *cstr) {
  53. int count = 0;
  54. bool inWord = false;
  55. for(int i = 0; cstr[i] != '\0'; i++) {
  56. if(!isspace(cstr[i])){
  57. if(!inWord){
  58. count++;
  59. inWord = true;
  60. }
  61. } else {
  62. inWord = false;
  63. }
  64. }
  65. return count;
  66. }
  67.  
  68. int countWords(const string &str){
  69. return countWords(str.c_str());
  70. }
Success #stdin #stdout 0s 5312KB
stdin
I have three cats
stdout
Enter a sentence: 
Word count (c-string version): 4
Word count (string version): 4