using strtok used more than once in the same function

so here's data.txt:
Hello World!
I'm a file.

here's the 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
31
#include<iostream>
#include<fstream>
#include<string.h>
#include<stdlib.h> // for system pause ...

using namespace std;

int main(){
    int datalen;
    ifstream ifdata("data.txt");
    ifdata.seekg(0, ios::end);
    datalen = ifdata.tellg();
    ifdata.seekg(0, ios::beg);
    char data[datalen], *word;
    ifdata.read(data,datalen);
    cout << "Starting Program" << endl << endl;
    word = strtok(data, " .,\n"); // first strtok
    while(word != NULL){ // keep going till strtok returns a NULL pointer
       cout << word << endl; // display the word found and enter a new line
       word = strtok(NULL, " .,\n"); // place in variable word the next word found in data string
    }
    // for some reason i want to repeat the process again.
    cout << "Repeating Starting Program" << endl << endl;
    word = strtok(data, " .,\n"); // i have no clue on what this does now
    while(word != NULL){ // keep going till strtok returns a NULL pointer // for some reasons it sops at the begining
       cout << word << endl; // display word, sometimes it gives me some random characters
       word = strtok(NULL, " .,\n"); // again don't know how this works the second time
    }
    system("pause"); //yes, yes i know all about system pause please don't argue about that...
    return (0);
}

so here's the output:
Starting Program

Hello
World!
I'm
a
file.
Repeating Starting Program

Hello
Press any key to continue . . .

and here's the expected output:
Starting Program

Hello
World!
I'm
a
file.
Repeating Starting Program

Hello
World!
I'm
a
file.
Press any key to continue . . .


can somebody tell me how to use strtok on the same string a second time ?
i mean :
1
2
3
4
5
word = strtok(data, " .,\n");
    while(word != NULL){
       cout << word << endl;
       word = strtok(NULL, " .,\n");
    }

2 times.
what should i write to make it word again ?
You should preserve the original string and use its copy with strtok. The problem that after using strtok the first time the original string is changed by inserted null characters.

Or you can read the original string from the file anew each time you are using strtok
Last edited on
You can use strcpy() to make a copy of the string before you begin, and use strtok() on the copy, not the original.
http://www.cplusplus.com/reference/clibrary/cstring/strcpy/
Topic archived. No new replies allowed.