NO

Author Topic: strtok  (Read 3319 times)

manichandra

  • Guest
strtok
« 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 .

Offline Bitbeisser

  • Global Moderator
  • Member
  • *****
  • Posts: 772
Re: strtok
« Reply #1 on: February 19, 2012, 06:06:17 PM »
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

  • Guest
Re: strtok
« Reply #2 on: February 19, 2012, 06:19:54 PM »
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
 
 
« Last Edit: February 19, 2012, 06:29:00 PM by CommonTater »

Offline DMac

  • Member
  • *
  • Posts: 272
Re: strtok
« Reply #3 on: February 20, 2012, 06:30:14 PM »
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:
Code: [Select]
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
Code: [Select]
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

  • Guest
Re: strtok
« Reply #4 on: February 20, 2012, 08:35:20 PM »
Hi DMac... I do it pretty much the same way, except I use a union...
Code: [Select]
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]);
« Last Edit: February 20, 2012, 08:36:51 PM by CommonTater »