//Charlotte Davies-Kiernan CS1A Chapter 10 P. 588 #3
//
/******************************************************************************
*
* Compute Word Counter
* ____________________________________________________________________________
* This program will accept a sentence from the user and return the number of
* words within it.
* ____________________________________________________________________________
* Input
* SIZE :Word limit for the input
* cstringInput :Cstring version of input
* strInput :string version of input
*
* Output
* wordCountCStr :Amount of words in the c-string
* wordCountString :Amount of words in the string.
*****************************************************************************/
#include <iostream>
#include <cstring>
#include <iomanip>
using namespace std;
//Function Prototypes
int countWords(const char *cstr);
int countWords(const string &str);
int main() {
//Data Dictionary
const int SIZE = 200;
char cstringInput[SIZE];
int wordCountCStr;
string strInput;
int wordCountString;
//Prompt User
cout << "Enter a sentence: " << endl;
cin.getline(cstringInput, SIZE);
//Count Words
wordCountCStr = countWords(cstringInput);
strInput = string(cstringInput);
wordCountString = countWords(strInput);
//Display!
cout << "Word count (c-string version): " << wordCountCStr << endl;
cout << "Word count (string version): " << wordCountString << endl;
return 0;
}
//Function Definitions
int countWords(const char *cstr) {
int count = 0;
bool inWord = false;
for(int i = 0; cstr[i] != '\0'; i++) {
if(!isspace(cstr[i])){
if(!inWord){
count++;
inWord = true;
}
} else {
inWord = false;
}
}
return count;
}
int countWords(const string &str){
return countWords(str.c_str());
}