User Name Password Register
DaniWeb IT Discussion Community
All
What is DaniWeb IT Discussion Community?
You're currently browsing the C section within the Software Development category of DaniWeb, a massive community of 427,988 software developers, web developers, Internet marketers, and tech gurus who are all enthusiastic about making contacts, networking, and learning from each other. In fact, there are 2,471 IT professionals currently interacting right now! Registration is free, only takes a minute and lets you enjoy all of the interactive features of the site.
Please support our C advertiser: Programming Forums
Jun 4th, 2005
Views: 14,939
Many times strtok is recommended for parsing a string; I don't care for strtok. Why?
  • It modifies the incoming string, so it cannot be used with string literals or other constant strings.
  • The identity of the delimiting character is lost.
  • It uses a static buffer while parsing, so it's not reentrant.
  • It does not correctly handle "empty" fields -- that is, where two delimiters are back-to-back and meant to denote the lack of information in that field.
This snippet shows a way to use sscanf to parse a string into fields delimited by a character (a semicolon in this case, but commas or tabs or others could be used as well).

Thanks to figo2476 for pointing out an issue with a previous version!
Thanks to dwks for asking why not to use strtok.
c Syntax | 4 stars
  1. #include <stdio.h>
  2.  
  3. int main(void)
  4. {
  5. const char line[] = "2004/12/03 12:01:59;info1;info2;info3";
  6. const char *ptr = line;
  7. char field [ 32 ];
  8. int n;
  9. while ( sscanf(ptr, "%31[^;]%n", field, &n) == 1 )
  10. {
  11. printf("field = \"%s\"\n", field);
  12. ptr += n; /* advance the pointer by the number of characters read */
  13. if ( *ptr != ';' )
  14. {
  15. break; /* didn't find an expected delimiter, done? */
  16. }
  17. ++ptr; /* skip the delimiter */
  18. }
  19. return 0;
  20. }
  21.  
  22. /* my output
  23. field = "2004/12/03 12:01:59"
  24. field = "info1"
  25. field = "info2"
  26. field = "info3"
  27. */
Comments (Newest First)
sanushks | Newbie Poster | 3 Days Ago
Hi,

This code does not work if there are successive delimiters with no info as shown below like
2007/09/15 12:34:23;;info1;info2;
The output is 2007/09/15 12:34:23
The rest of the string is ignored.

Please check
waldchr | Newbie Poster | Jun 18th, 2008
Dave Sinkula

How do I edit that code so it can have an input that can be changed?
Post Comment

Only community members can submit or comment on code snippets. You must register or log in to contribute.

DaniWeb Marketplace (Sponsored Links)
All times are GMT -4. The time now is 9:34 pm.
Forum system based on vBulletin Copyright ©2000 - 2008, Jelsoft Enterprises Ltd.
©2003 - 2008 DaniWeb® LLC