Using the strtok()/strtok_s() C function in C++ code program example

 

Compiler: Visual C++ Express Edition 2005

Compiled on Platform: Windows XP Pro SP2

Header file: Standard

Additional library: none/default

Additional project setting: Set project to be compiled as C++

Project -> your_project_name Properties -> Configuration Properties -> C/C++ -> Advanced -> Compiled As: Compiled as C++ Code (/TP)

Other info: none

To do: Find the next token in a string, using the current locale or a specified locale passed in. These functions are deprecated because more secure versions are available such as strtok_s(), _strtok_s_l(), wcstok_s(), _wcstok_s_l(), _mbstok_s(), _mbstok_s_l().

To show: How to use the strtok()/strtok_s() C functions in C++ code, as C++ wrappers

 

 

// the C strtok()/strtok_s() function in C++ code, using the C++ wrappers

// In this program, a loop uses strtok_s() to print all the tokens (separated by blanks)

#include <string>

#include <iostream>

using namespace std;

 

char string1[ ] = "A string\tof ,,tokens\nand some more tokens";

char string2[ ] = "Another string\n\tparsed at the same time.";

char separators[ ] = " ,\t\n";

char *token1, *token2, *next_token1, *next_token2;

 

int main(void)

{

cout<<"Tokens:"<<endl;

// establish a string and get the first token:

token1 = strtok_s(string1, separators, &next_token1);

token2 = strtok_s(string2, separators, &next_token2);

 

// while there are tokens in "string1" or "string2"

while ((token1 != NULL) || (token2 != NULL))

{

// get the next token:

if (token1 != NULL)

{

cout<<token1<<endl;

token1 = strtok_s(NULL, separators, &next_token1);

}

if (token2 != NULL)

{

cout<<" "<<token2<<endl;

token2 = strtok_s (NULL, separators, &next_token2);

}

}

return 0;

}

 

Output example:

 

Tokens:

A

    Another

string

    string

of

    parsed

tokens

    at

and

    the

some

    same

more

    time.

tokens

Press any key to continue . . .

 

 

C and C++ Programming Resources | C & C++ Code Example Index