Thursday, December 13, 2012
C++ Word finder and Word counter: List the words in a sentence and count the total number of words found
/*
PROGRAM: Word finder and Word counter
PURPOSE: List the words in a sentence and count the total number of words found
LANGUAGE: C++
AUTHOR: eternaltreasures
DATE: 2010 October 2
*/
#include <iostream>
#include <stdio.h>
#include <string>
using namespace std;
#define newline '\n'
char sentence [124];
int i;
int character_x;
int first_write_character = 0;
int wordcounter = 0;
void extractwords ()
{
//Start testing the sentence from the first character until the null character \0
for (i=0; sentence[i] != '\0'; i++)
{
//if a space is encountered, then write the words
if (sentence[i] == ' ')
{
wordcounter = wordcounter + 1;
for (character_x = first_write_character; character_x < i; character_x ++)
{
cout << sentence[character_x];
}
cout << newline;
first_write_character = i + 1;
}
}
}
//once the program detects the null character or empty string \0
//then this is the last word in the sentence input from the user
void extractlastword ()
{
wordcounter = wordcounter + 1;
for (character_x = first_write_character; character_x < i; character_x ++)
{
cout << sentence[character_x];
}
}
//this function displays the total word count in the given sentence
void countwords ()
{
cout << newline;
cout << newline;
cout << "Total words found: " << wordcounter;
}
//this is the main function of execution in the program
int main ()
{
cout << newline;
cout << "Please enter a sentence: ";
cout << newline;
gets (sentence);
cout << newline;
cout << "List of words found:";
cout << newline;
extractwords ();
extractlastword ();
countwords ();
return 0;
}
Subscribe to:
Post Comments (Atom)
No comments:
Post a Comment