Hey, I've decided to go back and learn C++ so I dug out my old book and found the following listing, but it gets stuck in the loop. I've checked and checked and can't see anything wrong :'(
I'm sorry if it's something obvious, I just got back from Vietnam yesterday so feeling a little jet-lagged hehe.
#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
Welcome to BleepingComputer, a free community where people like yourself come together to discuss and learn how to use their computers. Using the site is easy and fun. As a guest, you can browse and view the various discussions in the forums, but can not create a new topic or reply to an existing one unless you are logged in. Other benefits of registering an account are subscribing to topics and forums, creating a blog, and having no ads shown anywhere on the site.


Back to top










