0

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

3
Contributors
3
Replies
4
Views
12 Years
Discussion Span
Last Post by Acidburn
0

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

#include <cstring>
....

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

tokenPtr = strtok(sentance, " ");

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

>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;
}
This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.