What is the correct code using strtok to allow text to be entered separated by either a space, or /
?
I tried this, but its not working correctly:Code:p=strtok(input, "'/' ' '");
What is the correct code using strtok to allow text to be entered separated by either a space, or /
?
I tried this, but its not working correctly:Code:p=strtok(input, "'/' ' '");
here is an example with strtok:
Here space and comma are delimitersCode:#include <stdio.h> #include <string.h> int main() { char *p; p = strtok("Hello World"," "); printf(p); do { p = strtok('\0', ", "); if (p) printf("%s", p); } while (p); return 0; }
Mr. C
When i strchr is used to just allow for /, it works fine, but when i change it to strtok to allow for both / or a space, it outputs the wrong output. Any reason why this is happening?
Code:d=atoi(input); p=strtok(input, "/ "); m=atoi(++p); p=strtok(p, "/ " ); y=atoi(++p); initcalender(d,m,y);
one thing you should be aware of is to always use strtok on a copy of your string and not the string itself. strtok has a habit of modifying the string u pass it.
besides strtok should not really be used for delimiting. its use is for separating a string into its constituent tokens.To find a choice of delimiters check the functions in string.h especially strpbrk()
Last edited by Stoned_Coder; 09-13-2002 at 10:24 PM.
Free the weed!! Class B to class C is not good enough!!
And the FAQ is here :- http://faq.cprogramming.com/cgi-bin/smartfaq.cgi
Or you can use strchar() for filtering diliminers such as ; ?..
C-Dumbie
should read:Code:d=atoi(input); p=strtok(input, "/ "); m=atoi(++p); p=strtok(p, "/ " ); y=atoi(++p); initcalender(d,m,y);
Basically, you only want to pass strtok() a string the first time you call it. strtok() will actually keep track of which string it is currently working on, and when it is passed NULL as the first argument on subsequent calls, it will continue to try and tokenize the string it began working on with the first call.Code:d=atoi(input); p=strtok(input, "/ "); m=atoi(++p); p=strtok(NULL, "/ " ); y=atoi(++p); initcalender(d,m,y);
And if maintaining the original string is important, you will definitely be wanting to copy it first, as strtok() will chop up your string into the pieces you ask for.
A second alternative to your first question about token syntax is to actually create a string of seperators. This comes in handy if you will be using the same seperators a lot; it cuts down on typos:
Hope this helps,Code:char *seperators = " /";
starX
www.axisoftime.com