strtok_s use

Hey there,
I've been lurking for a while, and have gained a lot of knowledge...big thanks to everyone!

So, I was recently trying to puzzle using strtok_s, and thought I'd contribute my little set up.

-Regards

//**************

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
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
#include <iostream>
#include <fstream>
#include <sstream>
#include <string>

using namespace std;

// Example file contents:
// -ie; Simple individual lines of 3-doubles representing
//   each point's x, y, and z coordinates.
// -BUT...somebody added commas into the data file!
//
//	1.01, 2.02, 3.03
//	4.04, 5.05, 6.06
//	7.07, 8.08, 9.09
//
// etc...
//
const string points_filename("my_points_data.txt");

// CleanLine() function will strip away commas and excess whitespace
//  from a passed string argument, and returns a new clean one.
//
string CleanLine(const string& n)
{
	string cleanline;
	char* char_line = (char*)n.c_str(); // Non-const cast required.

	char* token		= NULL;
	char* context	= NULL;
	char  delims[]	= " ,\t\n";

	// During the first read, establish the char string and get the first token.
	token = strtok_s(char_line, delims, &context);

	// While there are any tokens left in "char_line"...
	while (token != NULL)
	{
		// Accumulate the tokens.
		cleanline += token;
		cleanline += ' ';

		// NOTE: NULL, function just re-uses the context after the first read.
		token = strtok_s(NULL, delims, &context); 
	}

	return cleanline;
}

// Example of using the CleanLine() function to clean the
//   simple 3D-mesh point data file lines of commas.
//
int main(void)
{
	ifstream in_fs(points_filename.c_str());
	if ( ! in_fs) cerr << "no points file\n";

	string line, cleanline;
	stringstream ss;

	double x, y, z;
	long point_count = 0;

	// Read through all the file lines, extract and display the cleaned data.
	//
	while (getline(in_fs, line)) {

		// Clean each line.
		cleanline = CleanLine(line);

		// Pass the cleaned-up string into a stringstream, to parse out the data elements.
		ss << cleanline;

		// Stringstream will parse directly on whitespace.
		ss >> x >> y >> z;					// TODO: Type compatibility checking.

		// Test display of output.
		cout << "For point number: " << point_count
			  << "\t x: " << x 
			  << "\t y: " << y 
			  << "\t z: " << z << endl;

		++point_count;
	}
}
AIEEEEEEEEEEEEEEEEEEEE No!

Never, ever, modify the buffer returned by string::c_str! Disaster waiting to happen!

You _must_ copy the string to a char array if you want to use strtok/strtok_s on it because
those functions modify the buffer.


(Ok, perhaps I overreacted a bit).
Topic archived. No new replies allowed.