Re: My own fuction: Access Violation error...
"Blue Streak" <rdlebreton@hotmail.com> ha scritto nel messaggio
news:839f1b64-d4e8-469e-a86e-d005133cf094@d21g2000prf.googlegroups.com...
Cannot be helped, old application uses char* all over the place and
I'm not re-writing the *whole* program.
OK, you do want to use char*.
However, I would really suggest to use a robust string class, and avoid
strtok (which has several problems, like exposing code to buffer overruns
attacks, etc.).
You may consider this code for splitting a string into substrings (and I
used std::string, so it is compatible with your need of char *):
<code>
typedef std::vector< std::string > StringList;
//
// Split a string into substrings using delimiters.
//
void Split(
StringList & substrings, // [out]
const std::string & s, // [in]
const std::string & delimiters )// [in]
{
// Clear output parameter
substrings.clear();
//
// Each token in input string is delimited by two "pointers":
// 'begin' and 'end'.
// These "pointers" (indexes in string) are updated during
// string splitting, they are moved scanning input string.
//
// Skip delimiters at beginning (if any)
string::size_type begin = s.find_first_not_of( delimiters, 0 );
// Find first non-delimiter
string::size_type end = s.find_first_of( delimiters, begin );
// Splitting loop
while (end != string::npos || begin != string::npos)
{
// Found a token: add it to the substring vector
substrings.push_back( s.substr( begin, end - begin ) );
// Skip delimiters
begin = s.find_first_not_of( delimiters, end );
// Find next non-delimiter
end = s.find_first_of( delimiters, begin );
}
}
</code>
You can use the Split function like this:
<code>
void TestSplit()
{
std::string input = "Jim Joe Jeff John";
StringList names;
Split( names, input, " ");
// Print substrings
int count = (int)names.size();
for ( int i = 0; i < count; i++ )
{
std::cout << names[i].c_str() << std::endl;
}
}
</code>
HTH,
Giovanni