#include <iostream>
#include <ctype.h>
#include <string.h>
using namespace std;
bool GetWord(char* theString, char * word, int& wordOffset);
int main() {
const int bufferSize = 255;
char buffer[bufferSize+1]; //hold the entire string
char word[bufferSize+1]; //hold the word
int wordOffset = 0; //start at the beginning
cout << "Enter a string: ";
cin.getline(buffer,bufferSize);
while (GetWord(buffer, word, wordOffset))
{
cout << "Got this word: " << word << endl;
}
return 0;
}
//function to parse words from a string
bool GetWord(char* theString, char* word, int& wordOffset)
{
if (theString[wordOffset] == 0) //end of string
return false;
char *p1, *p2;
p1 = p2 = theString + wordOffset; //Point to the next word
//eat leading space
for (int i = 0; i < (int)strlen(p1) && !isalnum(p1[0]); i++)
p1++;
//see if you have a word
if(!isalnum(p1[0]))
return false;
//p1 now points to start of next word
//p2 needs to point there to
p2 = p1;
//march p2 to end of the word
while(!isalnum(p2[0]))
p2++;
//p1 at beginning
//p2 at the end
//length of word is the difference
int len = int (p2 - p1);
//copy word into the buffer
strncpy (word,p1,len);
//null terminate at
word[len]='\0';
//now find the beginning of the next word
for (int j = int(p2-theString); j<(int)strlen(theString)
&& !isalnum(p2[0]); j++)
{
p2++;
}
wordOffset = int(p2-theString);
return true;
}I'm sorry if it's something obvious, I just got back from Vietnam yesterday so feeling a little jet-lagged hehe.

Help


Back to top










