// Elaine Torrez CS1A
// _____________________________________________________________
//
// COUNT WORDS IN STRING
// _____________________________________________________________
// This program prompts the user to enter a sentence and then
// determines the number of words in the sentence. A word is
// defined as a sequence of characters separated by spaces.
// _____________________________________________________________
// INPUT
// userStr : The sentence entered by the user
//
// OUTPUT
// words : Number of words in the sentence
// _____________________________________________________________
#include <iostream>
using namespace std;
// FUNCTION PROTOTYPE
int countWords(const char *str);
int main()
{
/****************************************************
* VARIABLE DECLARATIONS
****************************************************/
const int SIZE = 200;
char userStr[SIZE]; // INPUT sentence
int words; // OUTPUT word count
/****************************************************
* INPUT
****************************************************/
cout << "Enter a sentence: ";
cin.getline(userStr, SIZE);
/****************************************************
* PROCESS
****************************************************/
words = countWords(userStr);
/****************************************************
* OUTPUT
****************************************************/
cout << "\nNumber of words: " << words << endl;
return 0;
}
// *************************************************************
// countWords
// -------------------------------------------------------------
// Returns the number of words in a C-string. Words are counted
// by detecting transitions from spaces to non-space characters.
// *************************************************************
int countWords(const char *str)
{
int count = 0;
bool inWord = false;
for (int i = 0; str[i] != '\0'; i++)
{
if (str[i] != ' ' && !inWord)
{
// Starting a new word
inWord = true;
count++;
}
else if (str[i] == ' ')
{
inWord = false;
}
}
return count;
}