News:

Download Pelles C here: http://www.smorgasbordet.com/pellesc/

Main Menu

strtok

Started by manichandra, February 19, 2012, 06:11:49 AM

Previous topic - Next topic

manichandra

can anybody tell me the implementation of strtok function ??

i am attaching the original question . but i wanna know if there is anyway to do without using strtok .

Bitbeisser

Quote from: manichandra on February 19, 2012, 06:11:49 AM
can anybody tell me the implementation of strtok function ??

i am attaching the original question . but i wanna know if there is anyway to do without using strtok .
Well, the pseudo code kind of answers your question.
You need to keep looking for a delimiter character (the "." in case of an IPv4 address) in a string, keeping track of your current position within the string and copying the relevant part(s) of the string along the way...

Ralf

CommonTater

#2
Actually there's also a very sneaky way of doing this with sscanf() and a union... It's all about the formatter string in that case.

You can see an example of strtok here ... http://www.elook.org/programming/c/strtok.html


DMac

Here is how I  do an IP address.  I inferred this method from the Windows SDK headers and it just made sense to me.  I've never tried using strtok() for this sort of thing.  Perhaps this is the method //Tator had in mind.

String to IP:
DWORD IP_FromString(LPTSTR szIP)
{
// Assumes a properly formed IP string
//  A proper implementation should check
//  strlen() and formatting.

BYTE ip[4] = { 0, 0, 0, 0 };
_stscanf(szIP, _T("%hhd.%hhd.%hhd.%hhd"), &ip[3], &ip[2], &ip[1], &ip[0]);
return * (LPDWORD)ip;
}


IP to string

void IP_ToString(DWORD dwIP, LPTSTR buf, INT cchBuf)
{
// Assumes a buffer of sufficient length
BYTE ip[4];
*((LPDWORD)ip) = dwIP;
_stprintf(buf, cchBuf, _T("%d.%d.%d.%d"), ip[3], ip[2], ip[1], ip[0]);
}
No one cares how much you know,
until they know how much you care.

CommonTater

#4
Hi DMac... I do it pretty much the same way, except I use a union...

union t_IP
  { unsigned char bytes[4];
     unsigned long dword; }
  ip;

// string to dword
sscanf(szIP, "%hhd.%hhd.%hhd.%hhd", &ip.bytes[3], &ip.bytes[2], &ip.bytes[1], &ip.bytes[0]);
dwIP = ip.dword;

// dword to string
ip.dword = dwIP;
sprintf(szIP,"%d.%d.%d.%d",ip.bytes[3],ip.bytes[2],ip.bytes[1],ip.bytes[0]);