•
•
•
•
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
Many times
Thanks to figo2476 for pointing out an issue with a previous version!
Thanks to dwks for asking why not to use strtok.
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.
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.
#include <stdio.h> int main(void) { const char line[] = "2004/12/03 12:01:59;info1;info2;info3"; const char *ptr = line; char field [ 32 ]; int n; while ( sscanf(ptr, "%31[^;]%n", field, &n) == 1 ) { printf("field = \"%s\"\n", field); ptr += n; /* advance the pointer by the number of characters read */ if ( *ptr != ';' ) { break; /* didn't find an expected delimiter, done? */ } ++ptr; /* skip the delimiter */ } return 0; } /* my output field = "2004/12/03 12:01:59" field = "info1" field = "info2" field = "info3" */
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
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?
How do I edit that code so it can have an input that can be changed?
Post Comment
•
•
•
•
DaniWeb Marketplace (Sponsored Links)