954,492 Members — Technology Publication meets Social Media
Username:
Password:
Lost login information?
Have something to say? Contribute New Article Reply to this Article

Listing words in an Array of text

does anyone know the function that will take an array of text and cut it up into words and also cout different words;

ex. I prompt the user to input some text and the i send that text to a function that couts each different word on a new line

hopeolicious
Light Poster
43 posts since Oct 2004
Reputation Points: 11
Solved Threads: 0
 

You could tokenize it? ...
- this is a quote taken from my text book:

[php]
#include
....

char sentance[] = "This is a sentance";
char *tokenPtr;

tokenPtr = strtok(sentance, " ");

while(tokenPtr != NULL)
{
cout << tokenPtr <<"\n";
tokenPtr = strtok(NULL," ")
} //end while

[/php]

Acidburn
Posting Pro
511 posts since Dec 2004
Reputation Points: 12
Solved Threads: 5
 

>this is a quote taken from my text book
Your textbook misspelled sentence?

strtok is fine if you understand that it modifies the original string. This means that if you need the original for anything later, you need to make a copy first, and if the original string is const in anyway then you also need to make a writable copy. A better C++ solution is:

#include <iostream>
#include <sstream>
#include <string>

using namespace std;

void split_string ( const char *s )
{
  istringstream in ( s );
  string word;

  while ( in>> word ) {
    cout<< word <<endl;
  }
}

int main()
{
  const char *s = "This is a test";

  split_string ( s );
  cout<< s <<endl;
}
Narue
Bad Cop
Administrator
15,460 posts since Sep 2004
Reputation Points: 6,464
Solved Threads: 1,401
 

lol Sorry it was my typo...

Acidburn
Posting Pro
511 posts since Dec 2004
Reputation Points: 12
Solved Threads: 5
 

This article has been dead for over three months

Post: Markdown Syntax: Formatting Help
You