strtok() in array

Hello i want to save each word of the text in an array but i cant. This is my code:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
#include "stdafx.h"
#include <iostream>
#include <string>
using namespace std;

void main()
{
	char str[] = "are be, tva nema li da stane nai nakraq!";
	int wordCount = 0;
	
	char * p = strtok (str, " ,.!?");
	while (p != NULL)
	{
		p = strtok (NULL, " ,.-");
		wordCount++;
	}
	
	char** word = new char*[wordCount];
	for(int i=0;i<wordCount;i++)
		word[i] = new char[50];

	word[0] = strtok (str, " ,.!?");
	for(int i=1;i<wordCount;i++)
	{
		word[i] = strtok (NULL, " ,.!?");
	}
	
	for(int i=0;i<wordCount;i++)
		cout<< word[i]<<endl;
}


why don't work i have tried everything

The reference on this site wrote:
This end of the token is automatically replaced by a null-character by the function
Therefore you cannot call strtok several times on the same string. You could access each token with code like this:
1
2
3
4
5
const char* ptr = str;
for(int i = 0; i < wordCount; i++){
   cout << ptr;
   ptr += strlen(ptr)+1;
}

I'll explain. In the beginning your string was, for example, "Hello, world0". (0 here represents the terminating null character. After multiple calls to strtok the string is "Hello0 world0" so basically there are two strings now. If you have a pointer which points to 'H', to move it to the next word you have to add the length of "Hello0" which is strlen(ptr)+1. +1 because strlen doesn't count the null character.
1
2
3
4
5
6
7
while (p != NULL)
{
    /* p is not null; it points to a token;
       if you don't store it somewhere, the next line will make you lose it */
    p = strtok (NULL, " ,.-");
    wordCount++;
}
i want array with elements each word of the text! how to do that ?
Last edited on
either
-tokenize the string like you do
-allocate an array
-use my code, just replace the cout with copying the string.

or
-use std::vector with filipe's code. you may want to use std::string too.
vector is a sort of dynamic array. just push the strings onto it. (google how vectors work)
Topic archived. No new replies allowed.