C++ getting a word from a string help

Psynotic

New member
Joined
Nov 30, 2003
Messages
2
Im working on this program right now and it is supposed to count the words in a string and it is intelligent enough to not count puncuations as a word. My first funtion works, but i am having problems with my second. The second function gets a word number from the user and displays the correct word. For example, Hello my name is Amir. I want word 4 so i will display "is". Can anyone kindly help me thanks!

#include <iostream>
#include <fstream>
#include <string>

using namespace std;

int wordCount(string inputedText);
int getWord(int num, string selectedText);

int main()
{
int selectionNumber;
string selectionText;
string userText = "Power Overwhelming!";

cout<<userText<<endl;
cout<<"The number of words in the string is: "<<wordCount(userText)<<endl;
cout<<getWord(int num, string selectedText)<<endl;
system("PAUSE");

return 0;
}

int wordCount(string inputedText)
{
int wordCounter = 0;
unsigned int stringLength;
unsigned int n;
string delimiters = " !?,.;:@";

stringLength = inputedText.length();

for(n=0; n < stringLength; n++)
{
if(delimiters.find(inputedText[n]) != string::npos && n != 0)
{
if(delimiters.find(inputedText[n-1]) == string::npos)
{
++wordCounter;
}
}
if((n == stringLength-1)&&(delimiters.find(inputedText[n]) == string::npos))
{
++wordCounter;
}
}

return wordCounter;
}

int getWord(int num, string selectedText)
{
 
I had to change the signature of getWord. The one you had made no sense to me.

Code:
// Gets a word at a specified index.
// @param num the 0-based index of the word.
// @param selectedText the text to parse.
// @returns the word at the specified index.
// @exception range_error when the index is out of bounds.
string getWord(int num, string selectedText)
{
	--num;
	int wordCounter = 0;
	const string delimiters = " !?,.;:@";
	int stringLength = selectedText.length();
	string word = "";

	for(int n = 0; n < stringLength; n++)
	{
		if((delimiters.find(selectedText[n]) != string::npos) && (n != 0))
		{
			if(delimiters.find(selectedText[n-1]) == string::npos)
			{
				if(++wordCounter == num)
					return word;
				word.clear();
			}
		}
		else if((n == stringLength-1) && (delimiters.find(selectedText[n]) == string::npos))
		{
			++wordCounter;
			word.clear();
		}
		else
			word.push_back(selectedText[n]);
	}
	throw range_error("Index out of bounds.");
}
 
Back
Top